How to push an object in an Array

const animals = ['pigs', 'goats', 'sheep'];

animals.push({animal: 'cows'});

console.log(animals); // ["pigs", "goats", "sheep", { animal: "cows" }]
Answer from Soham on Stack Overflow
🌐
W3Schools
w3schools.com › jsref › jsref_push.asp
JavaScript Array push() Method
The push() method adds new items to the end of 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
Help: Pushing new objects into an array in JavaScript
Currently in the "JavaScript Loops, Arrays and Objects". While working on the objective of simply creating a list of objects in an array and then printing them, I decided to challenge myself more. To this end I tried to create a prompt set up that will do the following: Ask a series of 4 questions. Take the answers and create a new student object. Take that new student object and push ... More on teamtreehouse.com
🌐 teamtreehouse.com
1
April 22, 2018
Cannot use push on array
It seems like the program consider the “array” is not an Array Object, so I cannot use push there, just wondering why · I cleaned up your code. You need to use triple backticks to post code to the forum. See this post for details · You’re trying to push into a specific index (array[i]). ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
August 1, 2017
Trying to push to an array in an async function, array remains empty
Questions and posts about frontend ... to JavaScript on the backend. ... I have a function on a website backend I am making which does some uploads and saves some things to a database, but I am having trouble pushing values returned from an inner function to an array within the ... More on reddit.com
🌐 r/learnjavascript
1
1
July 27, 2021
🌐
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
As the push method, unshift modifies the original array and returns the new length of the modified array. Another method you can use to merge two arrays is the concat method.
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.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-array-push-method
JavaScript Array push() Method - GeeksforGeeks
The array push() function adds one or more values to the end of the array and returns the new length. This method changes the length of the array. An array can be inserted into the object with push() function.
Published   April 15, 2025
Find elsewhere
🌐
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 - This article will show you how to insert an element into an array using JavaScript. In case you're in a hurry, here are the methods we'll be discussing in depth in this article: // Add to the start of an array Array.unshift(element); // Add to the end of an array Array.push(element); // Add to a specified location Array.splice(start_position, 0, new_element...); // Add with concat method without mutating original array let newArray = [].concat(Array, element);
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Cannot use push on array - JavaScript - The freeCodeCamp Forum
August 1, 2017 - function largestOfFour(arr) { var array = []; for(var i = 0; i < arr.length; i++) { arr[i].sort(function(a,b) { return b - a; }); array[i].push(arr[i][0]); } return array; } largestOfF…
🌐
daily.dev
daily.dev › home › blog › get into tech › pop and push in javascript: array essentials
Pop and Push in JavaScript: Array Essentials
December 22, 2025 - Learn how to manipulate arrays with pop() and push() methods in JavaScript. Discover the basics of arrays, accessing elements, properties, and methods.
🌐
DEV Community
dev.to › technoph1le › the-javascript-arraypush-method-explained-5d4m
The JavaScript `Array.push()` method explained - DEV Community
November 24, 2022 - The Array.push() method adds one or more elements to the end of an array and returns the new length of the array.
🌐
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 - Append with push() and render in reverse (or reverse once at the end). Keep a small “recent items buffer” and merge it into the main list periodically. Use pagination/windowing: keep only the most recent N items in memory.
🌐
Medium
medium.com › an-idea › javascript-arrays-push-pop-shift-unshift-adc8fb815fc0
JavaScript Arrays: push(), pop(), shift() & unshift() | by Amanda M Johnson | An Idea (by Ingenious Piece) | Medium
October 10, 2021 - When working with arrays, it is important to understand the different types of methods and how they transform your data. push(), pop()…
🌐
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.
🌐
Shiksha
shiksha.com › home › it & software › it & software articles › programming articles › javascript array push
JavaScript Array Push - Shiksha Online
December 18, 2023 - The JavaScript array.push() method adds one or more elements to the end of an array, directly modifying the original array.
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Array › push
JavaScript Array push() - Add Elements to Array | Vultr Docs
September 27, 2024 - Initialize an array with some predefined values. Use the push() method to add a new element to the end of the array.
🌐
Stack Abuse
stackabuse.com › bytes › push-an-object-to-an-array-in-javascript
Push an Object to an Array in JavaScript
July 23, 2022 - To add multiple objects to an array, you can pass multiple objects as arguments to the push() method, which will add all of the items to the end of the array.
🌐
Scaler
scaler.com › topics › javascript-array-push
JavaScript Array push() Method - Scaler Topics
June 7, 2023 - In the example above, the push() ... array is displayed using console.log(). To append new element to the end of a JavaScript array, you can use the push() method....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › unshift
Array.prototype.unshift() - JavaScript | MDN
Array.prototype.push() has similar behavior to unshift(), but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters.