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
Trying to prevent duplicate values to be added to an array in JavaScript
You can use Set to remove duplicates from the array. https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array More on reddit.com
🌐 r/learnjavascript
13
8
November 14, 2021
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
August 2, 2021
How to push Array in to nested Object? I cant use .push() since im trying to add a new key value pair? Ive tried looking at stack overflow and other places but no luck. if anyone can point me in the right direction would be super helpful please :)
Push is an array method but your trying to add data to an object so that isnt going to work. To add data to an obect you need to either: obj.key = ['array'] obj['key'] = ['array'] If an object key is already an array you can: obj.key.push('something) edit: realised it is an array, so the above follows but you want: array[index].key = ['item'] array[index][key] = ['item'], or if already an array array[index][key].push('item) More on reddit.com
🌐 r/learnjavascript
9
22
March 6, 2022
People also ask

What is the fastest way to add an element to the beginning of a JavaScript array?
For arrays with fewer than 10,000 elements, unshift() provides the fastest performance when mutation is acceptable. For immutable operations, the spread operator offers the best combination of performance and readability. For very large arrays (100,000+ elements), consider using concat() or building a new array with a loop.
🌐
sencha.com
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 ...
Does unshift() modify the original array?
Yes, unshift() modifies the original array in place. It adds elements to the beginning and shifts existing elements to higher indices. If you need to preserve the original array, use the spread operator or concat() to create a new array instead.
🌐
sencha.com
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 ...
What is the difference between push() and unshift()?
push() adds elements to the end of an array, while unshift() adds elements to the beginning. Both methods mutate the original array and return the new length.
🌐
sencha.com
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 ...
🌐
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);
🌐
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
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript | MDN
5 days ago - A JavaScript array's length property and numerical properties are connected. Several of the built-in array methods (e.g., join(), slice(), indexOf(), etc.) take into account the value of an array's length property when they're called. Other methods (e.g., push(), splice(), etc.) also result in updates to an array's length property.
Find elsewhere
🌐
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.
🌐
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 - Adding elements to the beginning of an array, technically called prepending, is a fundamental operation in JavaScript programming. Unlike appending elements to the end using push(), prepending requires shifting all existing elements to higher indices, which has significant implications for ...
🌐
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.
🌐
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;
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › array.prototype.push()
JavaScript Array Push
November 6, 2024 - Use the JavaScript array push() method to append one or more elements to an array.