JavaScript has an Array reduce method which can be used on an array to kind of reduce it. To understand Array reduce method, let’s have a look at some reduce method examples.

JavaScript Array Reduce Example One

Let’s see how you can use Array.prototype.reduce to find sum of numbers inside an array.

let input = [10,20,30,40]
let output = input.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
});

console.log(`Sum is ${output}`)

reduce method takes a callback function which takes two parameter, accumulator and currentValue. The accumulator accumulates the result of each iteration and finally the output. So, when you return accumulator + currentValue, the value of accumulator for next iteration gets set. The default value of accumulator is the first item in the array.

JavaScript Array Reduce Example Two

Let’s see how you can use Array reduce to create a JSON array. Assuming you have a JSON object array which has too many keys.

let input = [
  {"name":"Sam","age":29,"gender":"male"},
  {"name":"Josh","age":29,"gender":"male"},
  {"name":"Simon","age":29,"gender":"male"},
  {"name":"Timon","age":29,"gender":"male"},
];

Now you want to create a JSON object array with some filtered keys, let’s say you want only the name key.

let input = [
  {"name":"Sam","age":29,"gender":"male"},
  {"name":"Josh","age":29,"gender":"male"},
  {"name":"Simon","age":29,"gender":"male"},
  {"name":"Timon","age":29,"gender":"male"},
];
// Reduce the input to get only the name key
let output = input.reduce((accumulator, currentValue) => {
  accumulator.push({"name" : currentValue.name});
  return accumulator;
},[]);

console.log(output)

The above code reduces the input array with only the name key.