reduce() in Java script

 Reduce () :

>Flatten the array - convert 3d or 2d array into a single-dimension array

>reduce method execute reducer function on each element , converting into a single output

> Mostly use when you want to single output like total sum, product or the total value

it takes four arguments:

1. accumulator

2. current value

3. current index

4. source array

Eg 1 - 

let arr1 = [2,3,4]

let hope = arr1.reduce((acccurrentValue,currentIndex,array=>{
    return acc += currentValue

});

console.log(hope);

Eg 2-

// Multiple each elemnt by 2
// return only those element which has value > 10
// return the sum of remaning element 

let arr = [234,5,6,7]

let newelement1 = arr.map((ele,index,array)=>  ele*2
).filter((ele)=> ele > 10).reduce((acc,ele=> {
    return acc+=ele
});

Eg 3 : 

multiply all elements in array


let arr1 = [2,3,4]

let hope = arr1.reduce((acccurrentValue,currentIndex,array=>{
    return acc = acc * currentValue
});
console.log(hope);


Eg 4:

Adding an element in array

let arr1 = [2,3,4]

let hope = arr1.reduce((acccurrentValue=>{
    debugger;
    return acc = acc + currentValue
},1);
console.log(hope);


0 Comments