Use the concat function, like so:
var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);
The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).
Use the concat function, like so:
var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);
The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).
In ECMAScript 6, you can use the Spread syntax:
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
console.log(arr1)
Spread syntax is available in all major browsers (that excludes IE11). For the current compatibility, see this (continuously updated) compatibility table.
However, see Jack Giffin's reply below for more comments on performance. It seems concat is still better and faster than the spread operator.
How to push an array into another array if the 1st item in the array to be pushed matches a string
Javascript - insert an array inside another array - Stack Overflow
Help: Pushing new objects into an array in JavaScript
How can I push an object into an array of array in react trough reducer?
Videos
Let's say I have the array of arrays:
groups = [ 0: ['FOLDER', 'file', 'last file'] 1: ['FOLDER', 'SUB folder', 'file', 'file', 'last file'] 2: ['SUB folder', 'file', 'last file'] 3: ['file', 'file', 'last file'] 4: ['FOLDER', 'last file', 'SUB folder', 'file', 'last file'] 5: ['last file'] ]
I want to push every sub-array in the "groups" array into the previous sub-array, if the sub-array's 1st item contains the 'last' or 'sub' strings. How do I do this?
This is what I'm trying but it doesn't work:
groups.forEach(function(group, i) {
if (group[0].includes('sub') || group[0].includes('last')) {
groups[i - 1].push(group);
}
}); So, for each sub-array in "groups" array, if the sub-array's first item contains string1 or string2, push it into the previous array in the loop.
Edit: thanks for the replies everyone, though I ended up going for a single one, I learned a bit about iteration from all of you.
You can use splice combined with some apply trickery:
a1 = [1,2,3,4,5];
a2 = [21,22];
a1.splice.apply(a1, [2, 0].concat(a2));
console.log(a1); // [1, 2, 21, 22, 3, 4, 5];
In ES2015+, you could use the spread operator instead to make this a bit nicer
a1.splice(2, 0, ...a2);
You can now do this if using ES2015 or later:
var a1 = [1,2,3,4,5];
var a2 = [21,22];
a1.splice(2, 0, ...a2);
console.log(a1) // => [1,2,21,22,3,4,5]
Refer to this for documenation on the spread (...) operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator