Use reduce to find largest/smallest value at index in array

I recently found a chunk of code to iterate through an array and find at what index the largest or smallest value exists using the reduce method. It’s very condensed and seems super efficient.

console.log([...Array(8)]
    .map(n => parseInt(giveMeANumber()))
    .reduce((p, c, i, a) => c > a[p] ? i : p, 0));

So here is what’s happening in order. First an array is initialized. The spread operator (…) is used to create the new Array of length 8. The spread operator spreads out the elements of the array. Here’s what that looks like.

[...Array(8)]; 
[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]

Second we are using the map method to place an integer value in each index of the Array calling the, as yet, undefined function giveMeANumber(). Which in practice would return an int or the string version of an int and not duplicate any values. Which would look like this.

[...Array(8)].map(n => parseInt(giveMeANumber())); 
[3, 5, 4, 9, 6, 1, 2, 0]

We are using the arrow function (=>) inside the map function to further simplify the code. Essentially,

n => parseInt(giveMeANumber());

Is the same as:

function (n) { parseInt(giveMeANumber()); }

Now we get to the meat of what is really happening here, the reduce method. Here is the definition from Mozilla. The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

The reducer function takes four arguments:

  1. Accumulator
  2. Current Value
  3. Current Index
  4. Source Array

Your reducer function’s returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value.

So our reducer function in this case is:

(p, c, i, a) => c > a[p] ? i : p

“p” stands for “previous” [previous array index] or Accumulator

“c” stands for “current” [array value] or Current Value

“I” stands for current “index” [of array] or Current Index

“a” stands for the full “array” [array] or Source Array

You can see we are using the the arrow function (=>) again here. And we are also using the Conditional (ternary) operator (?,:) to make the conditional more condensed. Which makes the below two functions identical.

(p, c, i, a) => c > a[p] ? i : p 

function (p, c, i, a) { 
    if (c > a[p]) { 
        return i;
    } else { 
        return p; 
    } 
}

All we are saying here is if the current value (c) is greater than the array (a) value at the previous index (p) then return the current index (i) or else return the previous index (p).

You could just switch the operator to find the smallest:

c < a[p]

So, running the complete code would look like this given that we are getting the same array from the map method above

> console.log([...Array(8)] 
    .map(n => parseInt(giveMeANumber())) 
    .reduce((p, c, i, a) => c > a[p] ? i : p, 0)); 
> 3

So, given our array above, it is correctly returning 3. Which is the index of the highest number in the array (9).

Leave a Reply

Your email address will not be published. Required fields are marked *