How to combine to arrays in JavaScript?
To combine to arrays in JavaScript, you can use the built-in array.concat() method. The array.concat() method takes arrays as arguments and returns the concatenated array. The concat() method takes one or more arrays as parameters and adds them to the array on which this method was called. The array.concat() method returns the newly created array after merging all the arrays passed as parameters to the method.
Where:
- array1, array2: one or more arrays are intended to be combined with the "array"
How to merge multiple arrays using spread operator in JavaScript?
You can concatenate JavaScript arrays using the spread operator. Write two or more variables inside an array, prefixed with a spread operator ("..."), and JavaScript will merge them into one new array.
Where:
- ...array1, ...array2: the arrays must be merged.
Merge JavaScript arrays with push() method
The array.concat() method and the spread operator create a new array, but sometimes it is necessary not to create a new array, but to modify an existing array. You can use the array.push() method for this. The push() method adds the provided elements to the end of the existing array.
You can also add one or more elements to the beginning of an array using the array.unshift() method:
Since the array.push() method can take multiple elements, we can append the entire array using the spread operator when calling the push() method: