Reducing Array Values to a Single Value in Javascript

Use-Cases of this Tutorial

  • Take an input array and get a single output value based on some condition.
  • Know the working of reduce() & reduceRight() methods.

There are situations where we would like to use an array's entries and get a single output from them. A simple example could be taking each element of an array and get the sum of all. This basically means that we are trying to reduce the array to a single value using some defined way.

For situations like these Javascript provides 2 methods that can be applied over arrays :

  • reduce()
  • reduceRight()

Both the methods accepts an array, processes each element of array as defined by a callback and returns an single output.

The reduce() Method

The reduce() method processes each element by traversing the array in the traditional left-to-right direction. The processing way is defined through a callback function — each element of array is passed through the callback.

When the callback processes a single element and gets a result, we need to save it when the next element gets processed. reduce() does this through an accumulator — it accumulates the return value from the callback, and this is used in the next iteration. When iteration over all elements is finished, it becomes the final return value of reduce().

Syntax of reduce looks like :

var output = some_array.reduce(function(accumulator, current_value, index){
	// process each element
}, initial_value);
  • The first parameter is the callback function. This function accepts 4 parameters :

    • accumulator : This collects the return values of the callback function from the last run.
    • current_value : This refers to the current element of the array that is being processed by the callback function.
    • index : This refers to the index of the current value in the array (optional)
    • calling_array : This refers to the calling array (optional)
  • The second parameter of reduce is the initial value for the accumulator. This is optional, and if not passed the first element of the array becomes the accumulator's value. In this case elements are passed from the second position as the first element has been set as the accumulator.

    If the initial value is passed then elements are passed from the first position.

    Important : Keep in mind that if the initial value is not passed, then elements will be processed from index=1. If initial value is passed then elements are processed from index=0.

reduce() is explained with some examples below.

// find sum of all elements in array
// we pass initial value for accumulator = 0

var arr = [1, 2, 3, 4, 5];

// "Index 0"
// "Index 1"
// "Index 2"
// "Index 3"
// "Index 4"
var sum = arr.reduce(function(acc, val, index) {
	console.log("Index : " + index)

	return acc + val;
}, 0);

// 15
console.log(sum);
// find sum of all elements in array
// initial value for accumulator is not passed

var arr = [1, 2, 3, 4, 5];

// "Index 1"
// "Index 2"
// "Index 3"
// "Index 4"
var sum = arr.reduce(function(acc, val, index) {
	console.log("Index : " + index);

	return acc + val;
});

// 15
console.log(sum);
// an array of objects
// find sum of key "x" of all objects, and add 100 to sum

var arr = [{ x : 1, y: 'a'}, { x : 2, y: 'b'}, { x : 3, y: 'c'} ];

// "Index 0"
// "Index 1"
// "Index 2"
var sum = arr.reduce(function(acc, val, index) {
	console.log("Index : " + index);

	return acc + val.x;
}, 100);

// 106
console.log(sum);
// Find the largest value in array

var arr = [56, 23, 86, 45, 20, 58];

// "Index 1"
// "Index 2"
// "Index 3"
// "Index 4"
// "Index 5"
var largest = arr.reduce(function callback(acc, cv, index) {
	console.log("Index : " + index);

	if(acc < cv)
		acc = cv;

	return acc;
});

// 86
console.log(largest);

The reduceRight() Method

This method is same as reduce() method, the difference being that this method traverses the array in right-to-left direction.

See the below example to see the difference between reduce() and reduceRight().

var arr = ["R", "A", "W"];

// "R"
// "A" 
// "W"
var str1 = arr.reduce(function callback(acc, cv) {
	console.log(cv);

	return acc.concat(cv);
}, '');

// "RAW"
console.log(str1);


// "W"
// "A" 
// "R"
var str2 = arr.reduceRight(function callback(acc, cv) {
	console.log(cv);

	return acc.concat(cv);
}, '');

// "WAR"
console.log(str2);

Useful Resources

Loading Comments