Javascript

Javascript loop through Array using Map Method

There are already many default method to loop through an Array in Javascript. But in this article, we are going to learn how we can loop through an array in Javascript using Map(), filter() and reduce() method.

Generally in any programming language, Loops offer a quick and easy way to do something repeatedly. It must be noted that there are many different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times.

Also Read: Best Javascript Interview Questions

This article is about a very different approach to loop through an array in javascript i.e by using Map, Filter, Reduce and Find method. So, let’s dive in.

Javascript loop through Array using Map Method

Javascript Map Method – This method creates a new array of the same length and calls a passed function on every element in the calling array. This property of the Array.map() method can help us to loop through an array when we want to perform something on every element of the Array. Here is an example of the same.

const performSomething = (item) => {
  //...
  return item
}
const items = ['a', 'b', 'c']
const newArray = items.map((item) => performSomething(item))

Javascript loop through Array using Filter Method

There is always a case in programming when we need to loop through an array to find or filter a certain element. We can do this using the Filter method instead of the default loop method in Javascript. Here is an example showing the same.

const items = [
  { name: 'a', content: { /* ... */ }},
  { name: 'b', content: { /* ... */ }},
  { name: 'c', content: { /* ... */ }}
]
const b = items.filter((item) => item.name === 'b')

Javascript loop through Array using Find Method

Sometimes you need to look for a specific item in the array and return it. We can easily do this with the array.find() method introduced in ES6. Here is an example showing how to do this.

const items = [
  { name: 'a', content: { /* ... */ }},
  { name: 'b', content: { /* ... */ }},
  { name: 'c', content: { /* ... */ }}
]
const b = items.find((item) => item.name === 'b')

So, this is all about how to loop through an array using Map, filter, find and reduce method in Javascript.

Leave a Comment