Skip to content

Foreach push to Array JavaScript | Example code

  • by

The forEach() array method is used to iterate through each item in an array. When using forEach, we have to specify a callback function. Foreach push to Array doesn’t work instead, use for loop in JavaScript.

for (var i = 0; i < a.length; i++) {
    if (a[i] == 1) a.push(5);
    console.log(a[i]);
}

Foreach push to Array JavaScript

A simple example code adds value to the array while looping.

<!DOCTYPE html>
<html>
<body>

  <script>
    var a = [1,2,3,4];
    var out = [];

    a.forEach(function(value){
      if(value == 1) 
        out.push(value);

    });
    console.log(out);
  </script>

</body>
</html> 

Output:

Foreach push to Array JavaScript

forEach() loop to populate an array

we have an array of objects like:

var fruits = [ {name:"banana", weight:150},{name:"apple", weight:95},{name:"orange", weight:160},{name:"kiwi", weight:80} ];

Populate a “heavy_fruits” array with items from the “fruits” array above which weight is > 100. Here is my code:

var heavy_fruits = [];
myfruit = {}; // here's your object

fruits.forEach(function(item,index) {
    if ( item.weight > 100 ) { 
        myfruit ["name"] = item.name;
        myfruit ["weight"] = item.weight; // you modify it's properties
    }

    heavy_fruits.push(myfruit); // you push it to the array
});

You end up with an array [myfruit, myfruit, myfruit, myfruit].

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS push topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading