JavaScript — Array loop methods

Array methods forEach, map, flatMap, filter, reduce, sort, some, every — simple examples

Photo by Émile Perron on Unsplash

In this article, I will show you how to use different JavaScript (ES6) array methods for looping over arrays. Some of these methods were not always that clear for me, so here they are simplified.

Note: this also applies for TypeScript

Looping

1 — forEach

The simplest one is forEach , it’s just designed to loop over an array, so you can use the single items. We are returning nothing.

const array = ['John', 'Jeroen', 'Peter']; array.forEach((name) => {

console.log(name);

}); // John

// Jeroen

// Peter

2 — map

The map method does almost the same as the previous method. Except now it returns a new array, with for example; modified items.

const array = ['John', 'Jeroen', 'Peter']; const mappedArray = array.map((name) => {

return `Hello ${name}!`;

}); console.log(mappedArray); // ['Hello John!', 'Hello Jeroen!', 'Hello Peter!']

3 — flatMap

An variation of map is flatMap , here you convert an array of one or more arrays into a single array, and map it.

const array = [['John'], ['Jeroen'], ['Peter']]; const flatMappedArray = array.flatMap((name) => {

return `Hello ${name}!`;

}); console.log(flatMappedArray); // ['Hello John!', 'Hello Jeroen!', 'Hello Peter!']

Minimizing values

4— filter

With filter we return a new array with only specific items. Sometimes we do not want every item in an array, we just want some of them.

const array = ['John', 'Jeroen', 'Peter']; const filteredArray = array.filter((name) => {

return name === 'Peter' || name === 'Jeroen';

}); console.log(filteredArray); // ['Jeroen', 'Peter']

5 — reduce

The most ‘complicated’ one I think is reduce , which you can use to change/reduce an array to a single value.

Most of the time it’s used for numbers. But it can also be used for strings, etc. Our first parameter is the accumulator which holds our previous values, the second parameter contains the currentValue we are looping over.

const array = [1, 2, 3]; const reduced = array.reduce((accumulator, currentValue) => {

return accumulator + currentValue;

}); console.log(reduced); // 6

Sorting

6— sort

In some cases, you want to sort on dates, alphabet or something else. Now the sort method is our guy. We need to specify two parameters because it will compare the values.

const array = ['John', 'Jeroen', 'Peter']; const sortedArray = array.sort((name1, name2) => name1.lowercase() < name2.lowercase()); console.log(sortedArray); // ['Jeroen', 'John', 'Peter']

Conditions

7— some

With some you are checking if one or more items in the array meet a certain condition. It returns true or false .

const array = ['John', 'Jeroen', 'Peter']; const hasName = array.some((name) => {

return name === 'Peter';

}); console.log(hasName); // true

8— every

With every you are checking if all items in the array meet a certain condition. This also returns true or false .