JavaScript Array#map(), reduce(), and filter()

In The Trouble With Loops I found these nice and simple examples covering Array#map(), Array#reduce(), and Array#filter().

const dollars = [32, 45, 50];

// map(): When you want to translate values in an array into another set of values.
const euros = dollars.map(eachAmount => eachAmount * .93);

// reduce(): When you want a total based on values in an array.
const sum = euros.reduce((total, amount) => total + amount, 0);

// filter(): When you want to remove unwanted values from an array.
const above30 = euros.filter(euro => euro >= 30);

If I still were in education, these examples would’ve made it into my course 🙂

Additionally, say you want to convert an array to an object with a certain field as its key. Again a typical thing to solve with Array#reduce():

const arrayToObject = (array, keyField) =>
   array.reduce((obj, item) => {
     obj[item[keyField]] = item
     return obj
   }, {});

const peopleArray = [
  { id: 123, name: "dave", age: 23 },
  { id: 456, name: "chris", age: 23 },
  { id: 789, name: "bob", age: 23 },
  { id: 101, name: "tom", age: 23 },
  { id: 102, name: "tim", age: 23 },
];
const peopleObject = arrayToObject(peopleArray, "id");

The value of peopleObject is:

{
  "123": { id: 123, name: "dave", age: 23 },
  "456": { id: 456, name: "chris", age: 23 },
  "789": { id: 789, name: "bob", age: 23 },
  "101": { id: 101, name: "tom", age: 23 },
  "102": { id: 102, name: "tim", age: 23 },
}

👉 Not too keen on those arrow functions? It’s time to lose the familiarity bias and embrace them.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.