map, reduce and filter

·

3 min read

map, reduce and filter

map, filter and reduce are higher-order functions in javascript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function.

map()

The map() is used to transform an array. You have an array, on which you want to perform some calculation and you don't want to mess with your original array. In this case, Map() method comes into the picture.

const numbers = [1,2,3,4];

const double = (num) => {
return num * 2;
}

const outputDouble = numbers.map(double)
console.log(outputDouble);  // [ 2, 4, 6, 8 ]

So the map() is a higher-order function as it's taking a function double as an argument. We can directly mention the function inside the map too.

const outputDouble = numbers.map((num) => {
return num * 2;
})

// OR 

const outputDouble = numbers.map((num) => num * 2)  // ES6 arrow function

filter()

The filter() method is used to filter the array. Suppose you have an array of numbers. You want to find out the odd numbers, or even numbers or numbers that are dividable by 3 or it could be anything.

const numbers = [1,2,3,4]

const isOdd = (num) => {
return num % 2;
}

const outputOdd = numbers.filter(isOdd);
// Or we can write like this too.
// const outputOdd =  numbers.filter(num => number % 2 );

console.log(outputOdd); // [ 1, 3 ]

reduce()

So, reduce method does not work just like its name, it's not reducing any element from the given array. The reduce() method reduce the whole array and gives a single value as a result.

For example, if we have an array of numbers and we want to perform the summation of all elements, or we want to find out the maximum number from the array, we can use reduce() method here.

// Find max
const numbers = [1,2,3,4]

const output = numbers.reduce((acc,curr)=>{
    if(curr > acc) return acc = curr
},0)

console.log(output) // 4

To remember the syntax of reduce(), there is a trick, always remember 2. This means, The reduce() function will take 2 arguments, 1st is the function and 2nd is the initial value of the accumulator. Now, the inside function takes 2 arguments as well. acc which is the accumulator and curr is the current value of the array. To understand this, let's find the max value without reduce() function.

const findMax = (num) => {
    let max = 0;
    for(let i =0; i< num.length; i++){
        if(num[i] > max){
            max = num[i]
        }
    }
    return max
}

console.log(findMax(numbers)) // 4

let's compare both functions. here, max is similar to acc variable. and curr is similar to num[i].