Tech Talk 03: JavaScript Map vs. Filter vs. Reduce
Sadat Rafsanjani
Software Engineer | SaaS Architect | AI Tinkerer | Open-Source Contributor | #Java #Python #AI
So without further due, lets get started.
Map
A map is an array function that operates on an array. We can pass a custom function inside it to perform some operation on an array.
Example:
Suppose, we have an array of numbers, we want to double each value. using map, it can be done very easily. There are two varaions, short hand and callback function approach.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(value => value * 2);
Output: [2, 4, 6, 8]
function doubleIt(n){
return n * 2;
}
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(doubleIt);
Output: [2, 4, 6, 8]
Filter
Similar to map, filter also performs on array but in a different approach. Filter applies condition on each element of the input array, if the condition is full filled, only then it is pushed to the output array otherwise discarded.
Example:
Suppose, from an array of numbers, we wan to sort out the even ones.
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(value => value % 2 === 0);
Output: [2, 4]
Reduce
This function takes an array and transform it to a single value. It is useful when we are trying to achieve some sort of transformed value out of an array.
Example:
Suppose, we want to get the total sum from an array of number.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, value) {
return result + value;
});
Output: 10
That's all folks!