The difference between javascript Array iteration methods

byGinkMon, 10 Oct 2016

.forEach()

The first and foremost method which is commonly used when you want to do something on each element of the array. This method doesn't return anything, just process the provided function on each element, one by one.

const list = [
  {id: 1, user: 'Mike'},
  {id: 2, user: 'Gink'},
  {id: 3, user: 'Lisa'},
  {id: 4, user: 'John'},
  {id: 5, user: 'Someone else'},
];
list.forEach(u => {
  console.log('Hello', u.user, 'your id is', u.id);
});

/* => Output:
 Hello Mike your id is 1
 Hello Gink your id is 2
 Hello Lisa your id is 3
 Hello John your id is 4
 Hello Someone else your id is 5
 */

Simple enough?

Just a little bit attention if you pass in a promise as the iterator. forEach() is blocking, but the iterator can be asynchronous. If we fire a promise in forEach() or any other builtin array methods in this article, it can only make sure the promises will be started in the order but keep in mind they'll run asynchronously.

If you encounter that issue and want to finish the first one before the next, you may want to use traditional for loop with await on the array instead of .forEach()

for (const u of users) {
  console.log('Hello', u.user, 'your id is', u.id);
  await doAsyncTask();
}

This one will make sure you finish saying hello, doing some async task on the first user before continue with the next one and so on.

.map()

You may need this one when you want to convert an array to a different manner. It works pretty similar to forEach() but will return another array, based on the function you provide to manipulate each element.

const list = [
  {id: 1, user: 'Mike'},
  {id: 2, user: 'Gink'},
  {id: 3, user: 'Lisa'},
  {id: 4, user: 'John'},
  {id: 5, user: 'Someone else'},
];
const listId = list.map(u => {
  return u.id;
});

console.log(listId);
/* => Output:
 [1, 2, 3, 4, 5]
 */

Now you have a new list with just user ID only, classic!

.filter()

This method returns another array also. But you can't manipulate the format like map(), you can only provide a condition to pick out some needed elements, not all. For example, you want to take a list with even id only:

const list = [
  {id: 1, user: 'Mike'},
  {id: 2, user: 'Gink'},
  {id: 3, user: 'Lisa'},
  {id: 4, user: 'John'},
  {id: 5, user: 'Someone else'},
];
const listEvenUser = list.filter(u => {
  return u.id % 2 == 0;
});
console.log(listEvenUser);

/* => Output:
 [ { id: 2, user: 'Gink' }, { id: 4, user: 'John' } ]
 */

So based on the return of the condition, if it's equal true, that element will be picked out.

.find()

Let's say you don't want to modify the list anymore, just wanna look for a user inside the list. Is there any user named Misaki, or John? Just pass a function with that name condition and see:

const list = [
  {id: 1, user: 'Mike'},
  {id: 2, user: 'Gink'},
  {id: 3, user: 'Lisa'},
  {id: 4, user: 'John'},
  {id: 5, user: 'Someone else'},
];
const foundMisaki = list.find(u => {
  return u.user == 'Misaki';
});
const foundJohn = list.find(u => {
  return u.user == 'John';
})
console.log(foundMisaki);
/* => Output:
 undefined
 */
console.log(foundJohn);
/* => Output:
 {id: 4, user: 'John'}
 */

Simply, now you got foundJohn which is the element of that user in the array, and foundMisaki is undefined because there's no user with that name inside the list.

.every()

In the contrast of .find() that picking only one element if existing. every() needs to iterate through the list and check if the provided condition will be satisfied by all elements. And then just return true or false.

const list = [
  {id: 1, user: 'Mike'},
  {id: 2, user: 'Gink'},
  {id: 3, user: 'Lisa'},
  {id: 4, user: 'John'},
  {id: 5, user: 'Someone else'},
];
const isAllPositive = list.every(u => {
  return u.id > 0;
});
const isAllEven = list.every(u => {
 return u.id % 2 == 0;
});
console.log(isAllPositive);
/* => Output:
 true
 */
console.log(isAllEven);
/* => Output:
 false
 */

That's it! You wanna check if all the users have positive id number, so it's true. But not all of them have even id number.

Summary

Above are some common cases you will see when working with array in Javascript. Of course the list of built-in methods is longer. You can check the full built-in array methods here.

You can also combine these methods to work in any way you want. For example:

const filterNames = list.filter(u => {
  return u.id % 2 == 0;
}).map(u => {
  return u.user;
});
console.log(filterNames);
/* => Output:
 [ 'Gink', 'John' ]
 */

Just keep in mind that each method call will iterate through the list once. So should not overuse it when your list is too long. If you can finish everything in only one loop, that's always better. If it's too complicated to combine, let's fall back to the loop for().


© 2016-2024  GinkCode.com