reduce()

input callback function and return sum of array value and set also initial value in callback function. ye humare arraye ke element ko sum karega.

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

// aim : sum of all the numbers in array 

 const sum = numbers.reduce((accumulator, currentValue)=>{
     return accumulator + currentValue;
 }, 100);

 const userCart = [
     {productId: 1, productName: "mobile", price: 12000},
     {productId: 2, productName: "laptop", price: 22000},
     {productId: 3, productName: "tv", price: 15000},
 ]

 const totalAmount = userCart.reduce((totalPrice, currentProduct)=>{
     return totalPrice + currentProduct.price;
 }, 0)

 console.log(totalAmount);

Posted

in

by

Tags: