Javascript reduce() method – Code Example

Total
0
Shares

In this article we will show you few code example on how to use Javasript reduce() method. It is used to run a function over all the elements of the array and return a final value.

Code Example –

1. Subtracting array numbers using reduce()

const numbers = [175, 50, 25];

console.log(numbers.reduce(myFunc));

function myFunc(total, num) {
  return total - num;
}

// Output - 100

2. Adding array entries using reduce()

const numbers = [15.5, 2.3, 1.1, 4.7];
console.log(numbers.reduce(getSum, 0));

function getSum(total, num) {
  return total + Math.round(num);
}

// Output: 24

Source: W3Schools


3. Adding array values using reduce() through inline function.

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;

const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);

// expected output: 10

Source: MDN


4. Removing Duplicate Entries using Reduce()

let ageGroup = [18, 21, 1, 1, 51, 18, 21, 5, 18, 7, 10];

let uniqueAgeGroup = ageGroup.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(uniqueAgeGroup); // [ 18, 21, 1, 51, 5, 7, 10 ]

Source: Programiz


5. Get total amount of the products in the shopping cart –

let shoppingCart = [
  {
    product: 'phone',
    qty: 1,
    price: 500,
  },
  {
    product: 'Screen Protector',
    qty: 1,
    price: 10,
  },
  {
    product: 'Memory Card',
    qty: 2,
    price: 20,
  },
];

let total = shoppingCart.reduce(function (previousValue, currentValue) {
  return previousValue + currentValue.qty * currentValue.price;
}, 0);

// Output: 550

Source: JavascriptTutorial