An Interest In:
Web News this Week
- April 3, 2024
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
Map, Reduce, and Filter - JS Array Functions Explained with Code
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 function
map() method creates a new array with the results of calling a function for every array element.
const output = arr.map(function) // this function tells map that what transformation I want on each element of array
Task 1: Double the array element
const arr = [1, 2, 3, 4, 5];// pass a function to mapconst double = arr.map(x => x * 2);console.log(double);// expected output: Array [2, 4, 6, 8, 10]
Task 2: Convert array elements to binary
const arr = [1, 2, 3, 4, 5];// Transformation logic:function binary(x) { return x.toString(2);}const binaryArr1 = arr.map(binary);console.log(binaryArr1) //[ '1', '10', '11', '100', '101' ]// The above code can be rewritten as :const binaryArr2 = arr.map(function binary(x) { return x.toString(2);//[ '1', '10', '11', '100', '101' ]})console.log(binaryArr2)// OR -> Arrow functionconst binaryArr3 = arr.map((x) => x.toString(2));console.log(binaryArr3)//[ '1', '10', '11', '100', '101' ]
Tricky MAP
const users = [ { firstName: "Neeraj", lastName: "Kumar", age: 25 }, { firstName: "Sandeep", lastName: "Kumar", age: 26 }, { firstName: "Mayank", lastName: "Roy", age: 25 }, { firstName: "Peter", lastName: "Mukherjee", age: 28 },];// Get array of full name : ["Neeraj Kumar", "Sandeep Kumar", ...]const fullNameArr = users.map((user) => user.firstName + " " + user.lastName);console.log(fullNameArr); // ["Neeraj Kumar", "Sandeep Kumar", ...]----------------------------------------------------------// Get the count/report of how many unique people with unique age are there// like: {25 : 2, 26 : 1, 28 : 1}const report = users.reduce((acc, curr) => { if(acc[curr.age]) { acc[curr.age] = ++ acc[curr.age] ; } else { acc[curr.age] = 1; } return acc; //to every time return update object}, {})console.log(report) // {25 : 2, 26 : 1, 28 : 1}
Filter function
Filter function is basically used to filter the value inside an array. The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method.
const array = [5, 1, 3, 2, 6];// filter odd valuesfunction isOdd(x) { return x % 2;}const oddArr = array.filter(isOdd); // [5,1,3]// Other way of writing the above:const oddArr = arr.filter((x) => x % 2);
Reduce function
It is a function which take all the values of array and gives a single output of it. It reduces the array to give a single output.
const array = [5, 1, 3, 2, 6];// Calculate sum of elements of array - Non functional programming wayfunction findSum(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { sum = sum + arr[i]; } return sum;}console.log(findSum(array)); // 17// reduce function wayconst sumOfElem = arr.reduce(function (accumulator, current) { accumulator = accumulator + current; return accumulator;}, 0); console.log(sumOfElem); // 17
// find max inside array: Non functional programming way:const array = [5, 1, 3, 2, 6];function findMax(arr) { let max = 0; for(let i = 0; i < arr.length; i++ { if (arr[i] > max) { max = arr[i] } } return max;}console.log(findMax(array)); // 6// using reduceconst output = arr.reduce((acc, current) => { if (current > acc ) { acc = current; } return acc;}, 0);console.log(output); // 6// acc is just a label which represent the accumulated value till now,// so we can also label it as max in this caseconst output = arr.reduce((max, current) => { if (current > max) { max= current; } return max;}, 0);console.log(output); // 6
Function Chaining
// First name of all people whose age is less than 30const users = [ { firstName: "Neeraj", lastName: "Kumar", age: 25 }, { firstName: "Sandeep", lastName: "Kumar", age: 26 }, { firstName: "Mayank", lastName: "Roy", age: 25 }, { firstName: "Peter", lastName: "Mukherjee", age: 28 },];// function chainingconst output = users .filter((user) => user.age < 30) .map((user) => user.firstName);console.log(output); // Homework challenge: Implement the same logic using reduceconst output = users.reduce((acc, curr) => { if (curr.age < 30) { acc.push(curr.firstName); } return acc;}, []);console.log(output);
Original Link: https://dev.to/neeraj1997dev/map-reduce-and-filter-js-array-functions-explained-with-code-2b2o
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To