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).

Answer from WiseGuyEh on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › push
Array.prototype.push() - JavaScript | MDN
The element(s) to add to the end of the array. The new length property of the object upon which the method was called. The push() method appends values to an array.
Discussions

How to push an array into another array if the 1st item in the array to be pushed matches a string
Since the other comment is useless, I will help out. Your code is close. Firstly, you need a third arg in your forEach function to reference the array you are looping thru: just add a third arg called groups because you already called it that within. Second, you need to be cautious of the case of the letters. Third, do not push the array. You need to use concat to join them; otherwise you push the whole array into the other, not just the values. Go back and fix these things. Still will not be perfect but these are good things to note/fix. Edit. Just a few btws: your code also has an issue that if the first subarray contains a keyword, an index out of bound error will be thrown. Also, the array that is added to the array before it will still exist. Your array length will not change. Not sure if this is your intention or not, just pointing it out. More on reddit.com
🌐 r/learnjavascript
6
3
November 10, 2023
Javascript - insert an array inside another array - Stack Overflow
If you want to insert another array into an array without creating a new one, the easiest way is to use either push or unshift with apply More on stackoverflow.com
🌐 stackoverflow.com
Help: Pushing new objects into an array in JavaScript
Dillon Wyatt is having issues with: Hello, I am working through the JavaScript course now. Currently in the "JavaScript Loops, Arrays and Objects". While working on the ob... More on teamtreehouse.com
🌐 teamtreehouse.com
1
April 22, 2018
How can I push an object into an array of array in react trough reducer?
Array#push returns the new length of an array . You can add an object to an array with the array spread operator: return [ ...state, { question: action.payload.question, answer: action.payload.answer, }, ]; More on reddit.com
🌐 r/learnreactjs
4
3
March 14, 2023
🌐
W3Schools
w3schools.com › jsref › jsref_push.asp
JavaScript Array push() Method
The push() method adds new items to the end of an array.
🌐
Reddit
reddit.com › r/learnjavascript › how to push an array into another array if the 1st item in the array to be pushed matches a string
r/learnjavascript on Reddit: How to push an array into another array if the 1st item in the array to be pushed matches a string
November 10, 2023 -

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.

Top answer
1 of 5
1
Since the other comment is useless, I will help out. Your code is close. Firstly, you need a third arg in your forEach function to reference the array you are looping thru: just add a third arg called groups because you already called it that within. Second, you need to be cautious of the case of the letters. Third, do not push the array. You need to use concat to join them; otherwise you push the whole array into the other, not just the values. Go back and fix these things. Still will not be perfect but these are good things to note/fix. Edit. Just a few btws: your code also has an issue that if the first subarray contains a keyword, an index out of bound error will be thrown. Also, the array that is added to the array before it will still exist. Your array length will not change. Not sure if this is your intention or not, just pointing it out.
2 of 5
1
Instead of using forEach() and trying to push into the current array during the iteration you create a new array with reduce(). In the callback if the index is 0 or the first element of the current array does not containt the substrings "last" or "sub", case-insensitive, there is no previous element to push the contents of the current array into, so we spread the new array and set the current array into a new array, else we push into the previous array and return the new array. let grouped = groups.reduce((a, b, index) => !index || !/last|sub/i.test(b[0]) ? [...a, b] : (a[a.length -1].push(...b), a) , []); // groups = grouped;
🌐
CodyHouse
codyhouse.co › blog › post › javascript-append-to-array
JavaScript quick tip - append to array with examples | CodyHouse
The user can drag and drop files multiple times; each time new files are dropped, the complete list of these files needs to be updated. We can use the push method with the spread operator to merge two arrays (the complete list of dropped files ...
🌐
freeCodeCamp
freecodecamp.org › news › how-to-insert-an-element-into-an-array-in-javascript
Push into an Array in JavaScript – How to Insert an Element into an Array in JS
November 7, 2024 - In case you're in a hurry, here ... = [].concat(Array, element); When you want to add an element to the end of your array, use push()....
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-add-array-to-array-of-array
JavaScript - Add Array to Array of Array - GeeksforGeeks
July 23, 2025 - The push() method is one of the most common ways to add an array to an array of arrays.
Find elsewhere
Top answer
1 of 1
1
Objects behave a bit differently from most other datatypes in JavaScript. When you assign an object to a variable or add it to an array or anything like that. JavaScript does not make a copy of the object, it makes the new variable (or array item) contain the exact same object you assigned. To illustrate this take a look at this code: ```JavaScript var example = { message: "Hello" }; var example2 = example; example.message = "world"; console.log(example2); ``` We create an object example then we create a new variable example2 and assign example to it. Then we change the message property of example and then we print out example2. Now what do you think will be printed out? If Objects worked like Strings and Numbers then you would expect { message: 'Hello' } to be printed out. Since that is what example contained when it was assigned to example2. But in reality the above code prints out { message: 'world' }. This is because these two variables don't hold independent copies of the object, they hold the exact same object. Which means that even though there are two variables at play there is actually only one object created in the above code. You just have two variables pointing at it. With that knowledge if you take a look at your code the behavior you experience should make a bit more sense. You create one object at the start of your code, then you assign it the details of one student. Then you add a pointer to that object to the array. Then you change that same object with details of a new student. Since you in reality only have one object you end up changing the values of that one object each time the loop runs. And adding that object to the array multiple times just creates multiple pointers to it. The solution to this issue is quite simple. Just create the object within the loop. Like this: ```JavaScript alert ("Hello"); var students = []; var tempNewStudentStorage; var finished; var questions = [ "What is the student's name?", "What Track(s) are they on?", "What achivement(s) have they gotten?", "What are their points?", ]; while (true) { var newStudent = { Name: "x", Track: "y", Achivement: 0, Points: 0, }; for (var i = 0; i < 4; i +=1) { tempNewStudentStorage = prompt(questions[i]); if (i === 0){ newStudent.Name = tempNewStudentStorage; } else if (i === 1){ newStudent.Track = tempNewStudentStorage; } else if (i === 2){ newStudent.Achievemnt = tempNewStudentStorage; } else if (i === 3){ newStudent.Points = tempNewStudentStorage; }; }; students.push(newStudent); finished = prompt("Are you done adding students? Y/N").toLowerCase(); while (finished.length > 1) { finished = prompt("Are you done adding students? Y/N").toLowerCase() }; if (finished === "y") { alert("Thank you for adding a new student!") break } else if (finished !== "y"){ continue; }; }; console.log(students); ``` That way you actually create a new object each time the loop runs, instead of reusing the object created at the start of the script. It's worth noting that Arrays and Functions also behave in the same way as I described above.
🌐
Medium
habtesoft.medium.com › add-elements-to-an-array-in-javascript-a9cc6cd9469f
Add elements to an array in JavaScript | by habtesoft | Medium
October 18, 2024 - In this example, we have an array of numbers and we use the push() method to add a single element and multiple elements to the end of the array. ... The splice() method can also be used to add elements to an array in JavaScript.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › concat
Array.prototype.concat() - JavaScript | MDN
The following code concatenates nested arrays and demonstrates retention of references: ... const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.log(numbers); // results in [[1], 2, [3]] // modify the first element of num1 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]]
🌐
Sentry
sentry.io › sentry answers › javascript › how to insert an item into an array at a specific index using javascript
How to insert an item into an array at a specific index using JavaScript | Sentry
January 30, 2023 - You can also use a for loop to loop through each item in an array, add each item to a new array, and insert an item at a specific index: ... const arr = ["walk the dog", "go shopping", "exercise"]; const index = 2; const value = "go to the pharmacy"; const newArr = []; for (let i = 0; i < arr.length; i++) { if (i === index) { newArr.push(value); } newArr.push(arr[i]); } console.log(newArr); // "walk the dog", "go shopping", "go to the pharmacy", "exercise" You can create a custom function that uses reduce() to insert an element into an array at a specific index:
🌐
React
react.dev › learn › updating-arrays-in-state
Updating Arrays in State – React
In this way, spread can do the job of both push() by adding to the end of an array and unshift() by adding to the beginning of an array.
🌐
freeCodeCamp
freecodecamp.org › news › insert-into-javascript-array-at-specific-index
How to Insert into a JavaScript Array at a Specific Index – JS Push
November 7, 2024 - They allow you to store and manipulate collections of data. Sometimes, you may need to insert a new element into an array at a specific index. To accomplish this task, you can use the push() method or the splice() method.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › from
Array.from() - JavaScript | MDN
A function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and mapFn's return value is added to the array instead.
🌐
Sololearn
sololearn.com › en › Discuss › 1699679 › how-to-push-and-array-into-another-array
How to push and array into another array | Sololearn: Learn to code for FREE!
February 23, 2019 - Here you go: var array1 = [{name: "Whitney"}, {name: "Cher"}, {name: "Tina"},{name: "Celine"}, {name: "Madonna"}, {name: "Janet"}]; var array2 = [{name: "Tina"}, {name: "Madonna"}]; function createNewArray() { var arr = []; for (var i = 0; i < array1.length; i++) { var j; for (var j = 0; j < array2.length; j++) { if (array1[i].name === array2[j].name) break; } if(j===array2.length) arr.push(array1[i]); } return arr; } array3 = createNewArray(); console.log("array3 = " + JSON.stringify(array3)); https://code.sololearn.com/Wvrx32Ax0AkD/#js
🌐
Sencha
sencha.com › home › blog › how to add elements to the beginning of an array in javascript (2026 guide)
How to Add Elements to the Beginning of an Array in JavaScript (2026 Guide)
March 14, 2024 - The spread operator is supported ... 11), transpilation with Babel is required. The concat() method merges two or more arrays into a new array without modifying the original arrays....
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Array › push
JavaScript Array push() - Add Elements to Array | Vultr Docs
September 27, 2024 - The push() method in JavaScript is an essential tool for manipulating arrays. It allows you to add one or more elements to the end of an array, modifying the array in place and returning the new length of the array.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-array-push-method
JavaScript Array push() Method - GeeksforGeeks
The push() method in JavaScript adds one or more elements to the end of an array and returns the new length of the array. It modifies the original array, increasing its length by the number of elements added.
Published   April 15, 2025
🌐
Stack Abuse
stackabuse.com › bytes › push-an-object-to-an-array-in-javascript
Push an Object to an Array in JavaScript
July 23, 2022 - You can also achieve the same thing by passing the object directly to the push() method, without first assigning it to a variable. let array = []; array.push({ name: 'Billy', age: 30, role: 'admin' }); console.log(array); // [{name: 'Billy', age: 30, role: 'admin'}]