Let's go over a few ways to combine arrays in Javascript!
Concatenate
We have two arrays, an array of numbers and an array of colors.
const numbers = [1, 2, 3]
const colors = ['red', 'blue', 'green']
const newArray = [].concat(numbers, colors) // method 1
const mutatedArray = numbers.concat(colors) // method 2
document.write(newArray)
We can use [].concat syntax to create a new empty array, and then add all the elements from our number and color arrays.
Since we're creating a new array, we are preserving immutability.
The second way of concatenation is to take an array and add the elements from the second array.
In our example, we would take our numbers array and add the elements from the colors array.
The result may look the same, but the second method actually mutates our numbers array.
If we wish to use our numbers array elsewhere, it won't have the same values that we started with.
Be careful!
Spread Operator
ES6 gave us a new method of combining arrays: the spread operator.
This specific syntax allows elements in an array to be expanded and accessed in a clean way.
const numbers = [1, 2, 3]
const colors = ['red', 'blue', 'green']
const newArray = [...numbers, ...colors]
document.write(newArray)
Instead of using concat(), we can simplify things by:
- Instantiating a new array
- Destructure and unpack elements from our numbers and colors array into our new array
Reduce
Another way to combine arrays is to use the reduce() method.
It is particularly useful when you want to perform a specific operation on each element in an array.
const numbers = [1, 2, 3]
const colors = ['red', 'blue', 'green']
const arrays = [numbers, colors]
const newArray = arrays =>
arrays.reduce((accumulator, next) => [...accumulator, next])
document.write(newArray(arrays))
In this case, we want to loop through all the elements of both of our numbers and colors array, and add them into our new array.
First, we create an array with both our numbers array and colors array.
Next, we pass this array to our reduce method, which returns a new array with the elements from the accumulator and the next item.
This happens to be our numbers array (accumulator) and colors array (next).
Flat
With ES2019, we now have access to the flat() method.
This new method creates a new array that recursively concatenates sub-array elements.
What does that mean?
Let's take a look at an example!
const numbers = [1, 2, 3]
const colors = ['red', 'blue', 'green']
const arrays = [numbers, colors]
const newArray = arrays.flat(arrays)
document.write(newArray)
Let's create an array, with our numbers array and colors array as elements.
Now, we have two different arrays inside an array.
We can use the flat() method to flatten the two inside arrays and return one array instead.
How convenient!
This is extremely useful, when you have nested arrays and arrays of different sizes.