JavaScript Array reduceRight()

Posted by

Understanding JavaScript Array reduceRight()

The Array.reduceRight() method applies a function against an accumulator and each element in the array (from right-to-left) to reduce it to a single value.

Syntax

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

arr.reduceRight(callback( accumulator, currentValue[, index[, array]] )[, initialValue])

[/dm_code_snippet]

Parameters

  • callback – Function to execute on each value in the array, taking four arguments:
    • accumulator – The accumulator accumulates the callback’s return values; it is the accumulated value previously returned in the last invocation of the callback—or initialValue, if it was supplied (see below).
    • currentValue – The current element being processed in the array.
    • index – The index of the current element being processed in the array.
    • array – The array reduceRight was called upon.
  • initialValue – Optional. Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduceRight on an empty array without an initial value is an error.

Return value

The single value that results from the reduction.

Description

The reduceRight() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Examples

Using reduceRight to sum all the values of an array

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduceRight(reducer));
// expected output: 10

[/dm_code_snippet]

Using reduceRight to flatten an array of arrays

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

const flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(
  (accumulator, currentValue) => accumulator.concat(currentValue)
);

console.log(flattened);
// expected output: [4, 5, 2, 3, 0, 1]

[/dm_code_snippet]

More information

For more information about using the Array.reduceRight() method, please refer to the MDN documentation.