Map(), filter() and reduce() in javasCript
Map()
JavaScript map() is a built-in function that allows you to process and transform all the items in a iterable without using an explicit for loop, a technique commonly known as mapping.
map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.
// double the all array itemsconst arr = [5,1,2,3,4];function double(x){return x * 2}const output = arr.map(double)console.log(output)
[ 10, 2, 4, 6, 8 ]Using Arrow function
Filter()const arr = [5, 1, 2, 3, 4];const output = arr.map(x => x * 2)console.log(output)
JavaScript filter() is aa built-in function that allows you to process an iterable and extract those items that satisfy a given condition.
This process is commonly known as a filtering operation. with filter() you can apply a filtering function to an iterable and produce new iterable with the items that satisfy that condition at hand.
// sepreate Even numbersconst arr = [5, 1, 2, 3, 4];function even(x) {return x % 2 == 0}const output = arr.filter(even);console.log(output)
[ 2, 4 ]Using Arrow function
reduce()// sepreate Even numbersconst arr = [5, 1, 2, 3, 4];const output = arr.filter(x => x % 2 == 0);console.log(output)
JavaScript reduce() is a function that implements a mathematical technique called folding or reduction.
reduce() is useful when you need to apply a function to an iterable and reduce it to a single cumulation value.
Ex.
//sum of all elementsconst arr = [1, 2, 3, 4, 5];function sum(arr) {let sum = 0for (let i = 0; i < arr.length; i++) {sum = sum + arr[i]}return sum}console.log(sum(arr))
15Using reduce method.
The reduce() method take a two argument 1st is a function and 2nd is a initial value. this function take a 2 parameter 1st is a accumulator and 2nd current. current represent each and every value of array. and accumulator represent the initial value.
const arr = [1, 2, 3, 4, 5];function addition(acc, curr) {acc = acc + currreturn acc}const output = arr.reduce(addition, 0);console.log(output)
const output = arr.reduce((acc, curr) => {return acc = acc + curr;}, 0);console.log(output)
Post a Comment