.map( ) .forEach( ) for( ). πŸ‘‰ Three ways for create an array and push it:

ljnce

Luca

Posted on August 21, 2020

.map( ) .forEach( ) for( ). πŸ‘‰ Three ways for create an array and push it:

Hi dev! πŸ‘©β€πŸ’» πŸ‘¨β€πŸ’»

I want to show you 3 different way for push a value intro your array empty, with the same result.

First of all, we have easy our array like this: πŸ—‚



var array = [
    {
        name: 'John'
    },
    {
        name: 'Meg'
    }
];


Enter fullscreen mode Exit fullscreen mode

In order by the most easiest, the first method is .map();
We need to create a new variable, take our array, and the return which value we need to push into this new variable:



var newArray = array.map(function(singleElement){
    return singleElement.name;
})

console.log(newArray); // return ['John', 'Meg']


Enter fullscreen mode Exit fullscreen mode

The second method is forEach(); we need to create a new empty array, and then call forEach() method for push our values into a new array created before:



var newArray = [];

array.forEach(singleElement =>{
    newArray.push(singleElement.name)
});

console.log(newArray); // return ['John', 'Meg']


Enter fullscreen mode Exit fullscreen mode

The third method is the classic one with a for() cycle.
We need to create new empty array, cycle our array, define the values you want to push into a new array, and then push it:



var newArray = [];

for (var i = 0; i < array.length; i++) {
    var singleElement = array[i];
    var name = singleElement.name;
    newArray.push(name);
}

console.log(newArray); // return ['John', 'Meg']


Enter fullscreen mode Exit fullscreen mode

The results is the same for all methods:

Alt Text

Hope this small article is interesting for you πŸ™‹β€β™‚οΈ

πŸ’– πŸ’ͺ πŸ™… 🚩
ljnce
Luca

Posted on August 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related