Hello everyone, I made a small recap of these super useful array functions in JavaScript: map, filter, find, reduce.
Let’s start defining our array.
Defining our array of objects
For example, we gonna use some fruits and their price and quantity.
const fruits = [
{
name: "Apple",
units: 3,
price: 0.25
},
{
name: "Mango",
units: 6,
price: 0.35
},
{
name: "Banana",
units: 4,
price: 0.15
},
];
Map function
Creates a new array from the original one.
In our case, we get a new array of strings to store the summary of our fruit’s info.
const summary = fruits.map((fruit, index) => {
const fruitCost = (fruit.price * fruit.units);
return `${fruit.units} units of ${fruit.name} costs $${fruitCost.toFixed(2)}`;
});
// Array of Strings
console.log(summary);
/*
[
'3 units of Apple costs $0.75',
'6 units of Mango costs $2.10',
'4 units of Banana costs $0.60'
]
*/
Filter function
Create a new array from the original one when a condition is met.
For us, we get a new array of fruit objects with fruits price lower than $0.20.
const acceptablePrice = 0.2;
const onlyCheaper = fruits.filter((fruit, index) => {
if (fruit.price < acceptablePrice) {
return true;
} else {
return false;
}
});
// Array of fruit Objects
console.log(onlyCheaper);
/*
[
{
name: "Banana",
units: 4,
price: 0.15
}
]
*/
Find function
Return the first object found (or undefined if not found) in the original array when a condition is met.
An example, we found the mango fruit info.
const search = "mango";
const findMango = fruits.find((fruit, index) => {
if (fruit.name.toLowerCase().includes(search)) {
return true;
} else {
return false;
}
});
// One fruit Object, without Array
console.log(findMango);
/*
{
name: "Mango",
units: 6,
price: 0.35
}
*/
Reduce function
Returns an accumulated (or reduced) value from the original array.
In our case, we calculated the cost of the fruits and accumulate them to get the total.
let initialValue = 0;
const grandTotal = fruits.reduce((accumulator, fruit) => {
const fruitCost = (fruit.price * fruit.units);
return accumulator + fruitCost;
}, initialValue);
// Number value
console.log(`Grand Total: $${grandTotal.toFixed(2)}`);
/*
Grand Total: $3.45
*/
Final thoughts
As you can see these concepts are easy to understand and are super useful in a development day.
I hope this will be useful to you as they are to me in my daily development road.
Also, this is a great book to easily learn javascript for beginners, check it out if you are interested in learning more about it: https://amzn.to/39Naqxs.
Here is a Python equivalent for these functions: https://hhsm95.dev/blog/python-useful-list-functions-map-filter-find-and-reduce/
Also, this is the full code: https://gitlab.com/-/snippets/2141007
PD. Yeah, I know that we can save up some lines but this is an understanding approach for the people learning JavaScript.