You have to create an object. Assign the values to the object. Then push it into the array:

var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Answer from user3589620 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.
๐ŸŒ
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 - The push() method is similar to the unshift() method as it adds an element to the end of an array rather than the beginning. It returns the length of the new array and, like the unshift() method, can be used to add more than one element. Let's try the same example again, but this time add them to the end of the array using the push() method:
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ javascript โ€บ standard-library โ€บ Array โ€บ push
JavaScript Array push() - Add Elements to Array | Vultr Docs
September 27, 2024 - Here, 4, 5, 6 are added to the numbers array in a single method call. The new length of the array is outputted, showing how push() has effectively increased the number of elements.
๐ŸŒ
CodyHouse
codyhouse.co โ€บ blog โ€บ post โ€บ javascript-append-to-array
JavaScript quick tip - append to array with examples | CodyHouse
The spread operator (...) expands the second_array so that it can be passed directly to the push method, with no need of looping through all its element.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ bytes โ€บ push-an-object-to-an-array-in-javascript
Push an Object to an Array in JavaScript
July 23, 2022 - let array = []; array.push({ name: 'Billy', age: 30, role: 'admin' }); console.log(array); // [{name: 'Billy', age: 30, role: 'admin'}] Another method, although less common, is to use the concat() method. This method is used to combine two arrays, which can also be used to simply add an object to an array. In this example we use concat() to add two objects to the array...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ javascript-array-push-method
JavaScript Array push() Method - GeeksforGeeks
Example: In this example, function func() initializes an array with elements 'GFG', 'gfg', 'g4g', then pushes the string GeeksforGeeks to the end of the array using the push() method.
Published ย  April 15, 2025
Find elsewhere
๐ŸŒ
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... Tagged with webdev, beginners, javascript.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-push-an-array-into-the-object-in-javascript
How to Push an Array into Object in JavaScript? | GeeksforGeeks
January 9, 2025 - ... // Creating a JS object to ... = ['Hello', 'World', '!!!']; // Pushing of array into arrayTwo Obj['arrayTwo'].push(arraynew); console.log(Obj.arrayTwo); ... JavaScript is best known for web page development but it is also ...
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.
๐ŸŒ
Programiz
programiz.com โ€บ javascript โ€บ library โ€บ array โ€บ push
JavaScript Array push()
The push() method takes in an arbitrary number of elements to add to the array. Returns the new (after appending the arguments) length of the array upon which the method was called. ... This method changes the original array and its length. To add elements to the beginning of an array, use ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ home โ€บ javascript โ€บ javascript array push method
Understanding JavaScript Array push Method
September 1, 2008 - The JavaScript Array push() method ... array and returns a new length after insertion. For Example, myArr.push('x', 'y') adds 'x' and 'y' to the end of myArr....
๐ŸŒ
JavaScript Tutorial
javascripttutorial.net โ€บ home โ€บ javascript array methods โ€บ array.prototype.push()
JavaScript Array Push
November 6, 2024 - let colors = ['red', 'green', 'blue']; let cmyk = ['cyan', 'magenta', 'yellow', 'back'];Code language: JavaScript (javascript) And you want to append the elements of the cmyk to the colors array.
Top answer
1 of 3
6

Your first snippet:

var row = new Array();
var newData = new Array();

for (i = 1; i <= 10 ; i++) {
    row[0] = i;
    newData.push(row);
}

pushes 10 times the reference to the array row, and at the same time changes the value contained in the position 0 of that array in turn to the values 1, 2, 3 .. 10, with the net result of setting the final contents of the row array to: [10].

The actual final value of newData is more correctly shown as:

[[10],[10],[10],[10],[10],[10],[10],[10],[10],[10]]

and not as:

 [10,10,10,...,10]

In JavaScript, pushing an object into an array, (as in this case an instance of the Array class), actually pushes into the array a reference to the object. Pushing the same variable row doesn't create multiple instances of it.

This behavior is explained in detail here: Is JavaScript a pass-by-reference or pass-by-value language?.

2 of 3
0

The first code sample doesn't return an array with [10, 10, 10, etc..] but an array with a single item: [10]. The push method basically adds every object to the given array. It will not add the items of an array if the given object is an array. It simple adds its like an object to the array, and determines the index based on the existing items.

Another way to add items to your array is using an index. Here are two samples which both result in the same array.

var arr = [];
for(var i = 0; i < 5; i++) {
    arr[i] = i;
}

[0, 1, 2, 3, 4]

var arr = [];
for(var i = 0; i < 5; i++) {
    arr.push(i);
}

[0, 1, 2, 3, 4]

Hope this helps

๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ how to use the array push() method in javascript
How to Use the Array push() Method in JavaScript - Tabnine
July 25, 2024 - How to Use the Array push() Method ... how to use the Array.push() method to add an element to an array: const fruits = ['peach', 'mango', 'banana']; fruits.push('strawberry'); console.log(fruits); // Expected output: // ["peach", ...
๐ŸŒ
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;