Three Ways to Combine Arrays in JavaScript
Easily and efficiently combine arrays in JavaScript.
Join the DZone community and get the full member experience.
Join For Free1. Concat()
The most basic way is using the concat() method. It's very simple; you just have to define two arrays and combine them as shown. (Remember the sequence matters.)
let firstArray = [1,2,3,'Shinchan']
let secondArray = ['Nohara',4,5,6]
let combinedArray1 = firstArray.concat(secondArray)
let combinedArray2 = secondArray.concat(firstArray)
console.log(`Combined Array1 = `+combinedArray1)
// Combined Array1 = 1,2,3,Shinchan,Nohara,4,5,6
console.log(`Combined Array2 = `+combinedArray2)
//Combined Array2= Nohara,4,5,6,1,2,3,Shinchan
2. Using a Spread Operator (ES6 Shortcut)
Now the second method is like a shortcut; you just have to store the values of two or more arrays in a different array using ellipses or spread operator. This is only available in the ES6 version. It's my favorite way to combine arrays, as it's very efficient.
As you can see, sequence matters here too.
let firstArray = [1, 2, 3, 'Shinchan']
let secondArray = ['Nohara', 4, 5, 6]
let thirdArray = [7, 8, 9, 'Himawari']
let combinedArray1 = [...firstArray, ...secondArray, ...thirdArray]
let combinedArray2 = [...secondArray, ...firstArray, ...thirdArray]
console.log('CombinedArray1 = ' + combinedArray1)
//Combined Array1 = 1,2,3,Shinchan,Nohara,4,5,6,7,8,9,Himawari
console.log('CombinedArray2 = ' + combinedArray2)
//Combined Array2 = Nohara,4,5,6,1,2,3,Shinchan,7,8,9,Himawari
3. Merge Arrays With Push
You can also use the push method to combine different arrays like as shown.
let firstArray = [1, 2, 3, 'Shinchan']
let secondArray = ['Nohara', 4, 5, 6]
let thirdArray = [7, 8, 9, 'Himawari']
let combinedArray = []
combinedArray.push(...firstArray, ...secondArray, ...thirdArray)
console.log(`CombinedArray = `+combinedArray)
// CombinedArray = [1,2,3,'Shinchan','Nohara',4,5,6,7,8,9,'Himawari']
First, declare an empty array and then use the push() method with the spread operator. The contents of the arrays will be copied in the desired array.
Remember, if you don't use the spread operator, then the whole array will be pushed and you will get a nested array called a two-dimensional array. (That is for another day’s discussion, so let’snot get into that.)
let firstArray = [1, 2, 3, 'Shinchan']
let secondArray = ['Nohara', 4, 5, 6]
let thirdArray = [7, 8, 9, 'Himawari']
let combinedArray = []
combinedArray.push( firstArray, secondArray, thirdArray)
console.log(`CombinedArray = `+combinedArray)
/* CombinedArray = [ [1,2,3,'Shinchan'],
['Nohara',4,5,6],
[7,8,9,'Himawari'] ]
That’s all. If you think there are any errors, or you want to provide some information feel free to comment below
Published at DZone with permission of Ashutosh Singh, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments