Javascript - multiple ways to add items into an array with examples

The push() method

The push() method is used to add one or more elements to the end of an array. It modifies the array in place and returns the new length of the array.

const numbers = [1, 2, 3];

// Add a new element to the end of the array
const newLength = numbers.push(4);

// The "numbers" array is now [1, 2, 3, 4]

You can also use the push() method to add multiple elements to an array at once, by passing in multiple arguments to the push() method. For example:

const numbers = [1, 2, 3];

// Add two new elements to the end of the array
const newLength = numbers.push(4, 5);

// The "numbers" array is now [1, 2, 3, 4, 5]

It's important to note that the push() method modifies the array in place, rather than returning a new array. This means that if you have a reference to the original array, the reference will still point to the modified array after calling push(). For example:

const numbers = [1, 2, 3];
const newNumbers = numbers;

numbers.push(4);

// The "newNumbers" array is also [1, 2, 3, 4]

The unshift() method

The unshift() method is a method in JavaScript that is used to add one or more elements to the beginning of an array and returns the new length of the array.

let fruits = ["banana", "orange", "apple"];

// Add a new element to the beginning of the array
let newLength = fruits.unshift("mango");

// fruits is now ["mango", "banana", "orange", "apple"]
// newLength is 4

In this example, we have an array of fruit names called fruits. We use the unshift() method to add the element mango to the beginning of the array. The unshift() method returns the new length of the array, which in this case is 4.

The splice() method

The splice() method is a method in JavaScript that is used to add, remove, or replace elements in an array. It can be used to insert new elements into an array at a specified position, or to remove elements from an array.

let fruits = ["banana", "orange", "apple", "mango"];

// Add a new element to the array at index 2
fruits.splice(2, 0, "grapes");
// fruits is now ["banana", "orange", "grapes", "apple", "mango"]

// Remove the third and fourth elements from the array
fruits.splice(2, 2);
// fruits is now ["banana", "orange", "mango"]

// Replace the first element with "pear"
fruits.splice(0, 1, "pear");
// fruits is now ["pear", "orange", "mango"]

In the first example, we use the splice() method to insert the element grapes into the array at index 2, without removing any elements. In the second example, we use splice() to remove the third and fourth elements from the array. In the third example, we use splice() to replace the first element in the array with pear.

The concat() method

The concat() method is a method in JavaScript that is used to merge two or more arrays. This method does not modify the existing arrays, but instead returns a new array that contains the elements of the merged arrays.

let fruits1 = ["banana", "orange", "apple"];
let fruits2 = ["mango", "grapes", "strawberry"];

// Merge the two arrays into a new array
let fruits = fruits1.concat(fruits2);

// fruits is now ["banana", "orange", "apple", "mango", "grapes", "strawberry"]
// fruits1 and fruits2 are unchanged

In this example, we have two arrays of fruit names called fruits1 and fruits2. We use the concat() method to merge these two arrays into a new array called fruits. The concat() method returns the new array, which contains all the elements from both fruits1 and fruits2, in the order in which they appear in the original arrays. Note that the original arrays, fruits1 and fruits2, are not modified by the concat() method.

The spread() method

The spread() operator is a syntax in JavaScript that allows an iterable (such as an array) to be expanded into individual elements. It can be used to expand an array into its elements, to pass each element of an array as a separate argument to a function, or to add the elements of one array to the beginning or end of another array.

let fruits = ["banana", "orange", "apple"];

// Expand the array into its individual elements
let first = ...fruits;
// first is "banana"

// Pass each element of the array as a separate argument to a function
let max = Math.max(...fruits);
// max is "orange"

let moreFruits = ["mango", "grapes", "strawberry"];

// Add the elements of moreFruits to the end of fruits
fruits = [...fruits, ...moreFruits];
// fruits is now ["banana", "orange", "apple", "mango", "grapes", "strawberry"]

// Add the elements of moreFruits to the beginning of fruits
fruits = [...moreFruits, ...fruits];
// fruits is now ["mango", "grapes", "strawberry", "banana", "orange", "apple"]

In this example, we have an array of fruit names called fruits. We use the spread operator to expand the array into its individual elements, and then use the Math.max() method to find the maximum value in the array (which is "orange" in this case). We also use the spread operator to add the elements of the moreFruits array to the beginning and end of the fruits array. The spread operator allows us to easily manipulate and combine arrays in a concise and convenient way.

The Map() method

The map() method is a method in JavaScript that is used to transform elements in an array. It applies a provided function to each element in the array, and returns a new array containing the transformed elements.

let numbers = [1, 2, 3, 4, 5];

// Multiply each element in the array by 2
let doubled = numbers.map(n => n * 2);

// doubled is now [2, 4, 6, 8, 10]

In this example, we have an array of numbers called numbers. We use the map() method to apply the function n => n * 2 to each element in the array, which multiplies each element by 2. The map() method returns a new array containing the transformed elements, which in this case are the doubled values of the original elements.

The Reduce() method

The reduce() method is a method in JavaScript that is used to reduce an array of values to a single value. It applies a provided function to each element in the array, starting from the first element and working its way towards the last element, and returns a single value that is the result of the reduction.

let numbers = [1, 2, 3, 4, 5];

// Sum the elements in the array
let sum = numbers.reduce((accumulator, current) => accumulator + current);

// sum is 15

In this example, we have an array of numbers called numbers. We use the reduce() method to sum the elements in the array. The reduce() method takes a function as an argument, which specifies how to reduce the array. In this case, the function adds the current element to the accumulator (which is the running total of the sum), and returns the updated accumulator. The reduce() method returns the final value of the accumulator, which in this case is the sum of all the elements in the array.

The Array.from() method

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object. It is commonly used to convert an array-like object, such as a NodeList returned from a querySelectorAll() call, into a true Array that can be used for more advanced operations like map() and reduce().

Here is an example of how you can use Array.from() to convert a NodeList into an array:

const nodeList = document.querySelectorAll('p');
const array = Array.from(nodeList);

Now that the nodeList has been converted into an array, we can use array methods like map() and forEach() on it:

array.forEach(function(node) {
  node.classList.add('paragraph');
});

It's important to note that Array.from() creates a shallow-copied version of the original array-like object, which means that the new Array instance will only have a shallow copy of the elements in the original object. This means that if the original object contained any nested arrays or objects, those nested objects will be shared between the original object and the new Array instance.

Conclusion

In summary, there are many ways to modify array item values in JavaScript. Some of these methods include push(), splice(), unshift(), concat(), map(), spread(), reduce(), and Array.from(). Each of these methods has its own specific use case and can be useful in different situations. It's important to understand the differences between these methods and how to use them effectively in your own code.