Replace your loops by Array methods - map()

Fernando Daciuk
Daily JS Tips
Published in
2 min readJan 28, 2016

In the last article, I wrote about forEach() method. In these, I will show you the map() method :)

One thing I had not shown, is about second argument of the forEach(). You can pass an object - in this case, an array -, that will be the `this` inside the forEach callback function:

[1, 2, 3].forEach(function(item, index) {
console.log(this[index]);
}, [4, 5, 6]);
// 4
// 5
// 6

As you can see, the `this` object, points to array [4, 5, 6], not to [1, 2, 3].

The `map()` method works like `forEach()`: this method iterates by an array, and receives two parameters: a callback function, and a second parameter, that represents the `this`, inside callback function. The second parameter is optional, and you’ll rarely need it.

The big difference between this two methods is that the `map()` method returns a new array, while `forEach()` doesn’t returns anything. Look this example:

var products = [{
id: 0,
name: 'Product 1'
},{
id: 1,
name: 'Product 2'
}];

We’ve an array of products, that has two properties: `id` and `name`. If you want to get all ids, you can use `map()` method:

var productsIds = products.map(function(product) {
return product.id;
});
console.log(productsIds); // [0, 1]

The signature of callback method is the same as `forEach()`: the first argument is the item that is being iterated. The second argument is the index, and the third one is a pointer to array that is being used.

The return of the callback function, is the item that will be saved on the new array (`productsIds`).

In the above example, we are returning the `product.id`. `product` is the object that is being iterated:

/* 
First iteration:
{ id: 0, product: 'Product 1' }
Second iteration:
{ id: 1, product: 'Product 2' }
*/

And `id` is a property of this object.

Pretty simple, han? This is better than use a for loop:

var productsIds = [];
for(var i = 0; i < products.length; i++) {
productsIds.push(products[i].id);
}
console.log(productsIds); // [0, 1]

The `map()` method is much more clear than for loop ;)

And if you use it with arrow functions, this will be more clear yet:

var productsIds = products.map(product => product.id);
console.log(productsIds); // [0, 1]

That’s it for now! Wait for the next posts :D

See ya!

--

--