Map, Filter and Reduce

Map, Filter and Reduce

Map, reduce, and filter are all array methods 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. In a nutshell is a more Syntactically sugared way of writing loops in Js

Map

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Syntax

var new_array = arr.map(function callback(element, index, array) {
    // Return value for new_array
}[, thisArg])

In the above example, Element is the value of element at that particular Index, Element refers the postion in array, Array is the copy of original array which could be used as a conditional for the upcoming render or the returned array.

In the callback, only the array element is required. Usually some action is performed on the value and then a new value is returned.

Example In the following example, each number in an array is doubled.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]

The below example involves uses of all the arguments for Better understanding.

const oldArray = [16, 9, 4, 1];

const newArray = oldArray.map((val, index, arr) => {
  let nextItem = index + 1 < arr.length ? arr[index + 1] : 0
  return val - nextItem;
});

// newArray = [7, 5, 3, 1]

Filter

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Syntax

var new_array = arr.filter(function callback(element, index, array) {
    // Return true or false
}[, thisArg])

The syntax for filter is similar to map, except the callback function should return true to keep the element, or false otherwise. In the callback, only the element is required.

Examples In the following example, odd numbers are "filtered" out, leaving only even numbers.

const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]
In the next example, filter() is used to get all the students whose grades are greater than or equal to 90.

const students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
];
const studentGrades = students.filter(student => student.grade >= 90);
return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]

Reduce

The reduce() method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.

Syntax

arr.reduce(callback, [initialValue])

function callbackFn(previousValue, currentValue, currentIndex, array){ ... }

The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.

accumulator - the returned value of the previous iteration currentValue - the current item in the array index - the index of the current item array - the original array on which reduce was called The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function. Examples The following example adds every number together in an array of numbers.

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, item) {
  return result + item;
}, 0);
console.log(sum); // 10

In the next example, reduce() is used to transform an array of strings into a single object that shows how many times each string appears in the array. Notice this call to reduce passes an empty object {} as the initialValue parameter. This will be used as the initial value of the accumulator (the first argument) passed to the callback function.


var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'duck', 'rabbit'];

var petCounts = pets.reduce(function(obj, pet){
    if (!obj[pet]) {
        obj[pet] = 1;
    } else {
        obj[pet]++;
    }
    return obj;
}, {});

console.log(petCounts); 

/*
Output:
 { 
    dog: 2, 
    chicken: 2, 
    cat: 1,
    duck: 1, 
    rabbit: 1 
 }
 */

Refrences:

developer.mozilla.org

freecodecamp.org

youtube.com/watch?v=zdp0zrpKzIE

Thanks for Reading!