Map, Filter and Reduce are the most commonly used methods in Javascript. These methods allow you to work with arrays.
Map
The map()
method returns a new array containing the results of applying an operation on all the original array elements.
const numbersArr = [1, 2, 3, 4, 5, 6];
const doubledNumbers = numbersArr.map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10, 12]
Filter
The filter()
method returns a new array containing the array elements that passes the condition provided within filter method.
const numbersArr = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbersArr.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]
Reduce
The reduce()
method returns a single output value based on the reducer function(that we provide). This reducer function runs on each element of an array resulting in a single output value.
const numbersArr = [1, 2, 3, 4, 5, 6];
const sum = numbersArr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 21
Reduce method is a bit tough to wrap your head around. It was the same for me too for a while. Then, when I started using it, it became clearer with every usage.
You can also combine these methods to perform more complex operations (which is sometimes required in real life projects).
const numbersArr = [1, 2, 3, 4, 5, 6];
const result = numbersArr
.map(num => num * 2)
.filter(num => num > 5)
.reduce((sum, num) => sum + num, 0);
console.log(result); // 36
The order in which these methods are used is not necessarily the same. It can vary depending on the result we want.
For More information, please refer to MDN Docs.
#map #filter #reduce #javascript #coding #softwareEngineer