Concatenating Arrays
suggest changeTwo Arrays
const array1 = [1, 2];
const array2 = [3, 4, 5];
const array3 = array1.concat(array2); // returns a new array
const array3 = [...array1, ...array2]
Results in a new Array:
[1, 2, 3, 4, 5]
Multiple Arrays
const array1 = ["a", "b"];
const array2 = ["c", "d"];
const array3 = ["e", "f"];
const array4 = ["g", "h"];
Provide more Array arguments to array.concat()
const arrConc = array1.concat(array2, array3, array4);
Provide more arguments to []
const arrConc = [...array1, ...array2, ...array3, ...array4]
Results in a new Array:
["a", "b", "c", "d", "e", "f", "g", "h"]
Without Copying the First Array
const longArray = [1, 2, 3, 4, 5, 6, 7, 8];
const shortArray = [9, 10];
Provide the elements of shortArray as parameters to push using Function.prototype.apply
longArray.push.apply(longArray, shortArray);
Use the spread operator to pass the elements of shortArray as separate arguments to push
longArray.push(...shortArray)
The value of longArray is now:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If the second array is very long (on the order of 100,000 entries), apply or a spread argument list can throw a RangeError because each element becomes an argument. Iterate instead:
shortArray.forEach(function (elem) {
longArray.push(elem);
});
Array and non-array values
const array = ["a", "b"];
const arrConc = array.concat("c", "d");
const arrConc = [...array, "c", "d"]
Results in a new Array:
["a", "b", "c", "d"]
You can also mix arrays with non-arrays
const arr1 = ["a","b"];
const arr2 = ["e", "f"];
const arrConc = arr1.concat("c", "d", arr2);
Results in a new Array:
["a", "b", "c", "d", "e", "f"]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents