Replace your loops by Array methods

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

It is very common to use loops on our codes, when we work with big amounts of data.

And in most time, this data come from an array. So, we make something like this:

var data = [
{
id: 1,
title: 'Title 1'
},
{
id: 2,
title: 'Title 2'
}
];
for(var i = 0, len = data.length; i < len; i++) {
console.log(data[i].id, data[i].title);
}

And everytime who we need handle this data, we use loops.

For example, to get object that has even id:

var even = [];
for(var i = 0, len = data.length; i < len; i++) {
if(data[i].id %2 === 0) {
even.push(data[i]);
}
}
console.log(even); // { id: 2, tite: 'Title 2' }

To check if any object has an id = 1:

var hasID1 = false;
for(var i = 0, len = data.length; i < len; i++) {
if(data[i].id === 1) {
hasID1 = true;
break;
}
}
console.log(hasID1); // true

And lots of other examples that we can do with loops. To improve your job, we can use Array metods.

The Array object has some methods to work with data, instead use traditional loops. And the first method that we will see today is forEach().

forEach() is a method of Array object, that returns nothing.
Your signature is:

array.forEach(callback);

And his callback signature is:

function(item, index, array) {}

When `item` is the array item; `index` is the array item index; and the last argument, `array`, is the original array. So, for every item in array, this function will be executed once. Look this example, using the same data who we use before:

data.forEach(function(item, index, array) {
console.log(item.id, item.title);
});

This is just a simple example to show you how it works! Clearly, the code is more readable than the previous, using `for` loop.

But this is just an intro! I will show you some other powerfull array methods on the next posts! Stay tuned! :D

See ya!

--

--