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.
Leave a comment