JavaScript Array Methods ForEach, Map, and Reduce

Ignacio Ojanguren
2 min readNov 14, 2021

--

ECMAScript 2015 introduced some new array functions to help developers handle arrays.

I will go over some of these functions that JavaScript introduced, which are forEach, map, and reduce. These functions were introduced to reduce common issues developers had when modifying arrays. The most common issues were writing inefficient array iterations, and mutating existing arrays.

forEach

Use forEach when you want to iterate over an array, and you DON’T want to modify the content of the array.

forEach receives a callback function, and the required parameter of the function is each value in the array.

const userNames = [
{ firstName: 'Test1' },
{ firstName: 'Test2' },
{ firstName: 'Test3' }
]
userNames.forEach((user) => console.log(user.firstName))// The console log will be:
// Test1
// Test2
// Test3

map

Use map when you want to MODIFY the values of the array. Map will assign the values to a new array, so it won’t mutate the original array. REMEMBER: In JavaScript you don’t want to mutate arrays!

map receives a callback function, and the required parameter of the function is each value in the array. The callback has to return the new value that wants to be assigned to that array value.

const emails = [
'invalid @test.com',
'valid@test.com',
'wro ng@test.com'
]
const cleanEmails = emails.forEach((email) => {
return email.replace(/\\s+/g,""); // Remove empty spaces
})
console.log(cleanEmails)// Console log:
// [
// 'invalid@test.com',
// 'valid@test.com',
// 'wrong@test.com'
// ]

reduce

Use reduce when you want to modify the data structure of the array wrapping the values, and the values.

reduce receives a callback function. The required parameter of the callback function is the accumulator(data structure that is going to contain the new values), and the element being iterated in the array.

The goal of this example is to convert the data structure from an array to an object, and the key of the objects will be the id.

const users = [
{ id: 1, firstName: 'Ignacio', lastName: 'Ojanguren' },
{ id: 2, firstName: 'Testing', lastName: 'Test' },
{ id: 3, firstName: 'First', lastName: 'Name' },
]
// newUser is the accumulator object
// user is the value in the array
const newObject = users.reduce((newUsers, user) => {
return { ...newUsers, [user.id]: user }
}, {});
console.log(newObject)```
Console Log result
{ 1: {
id: 1,
firstName: “Ignacio”,
lastName: “Ojanguren”
},
2: {
id: 2,
firstName: “Testing”,
lastName: “Test”
},
3: {
id: 3,
firstName: “First”,
lastName: “Name”
}
}
```

For more information about these functions check the original documentation: forEach, map, and reduce

--

--

Ignacio Ojanguren

Over 3 years of experience as a Software Engineer at Privy, recently acquired by Attentive Mobile. I am Learning, and I hope I can share what I learn with you.