Tools for working with arrays

INPUT · Slides

Folding into one value

01 / 05

Gathering everything into one

To sum every element in an array, up to now we put let total = 0; outside a loop and added items one by one.

"Summing everything up" and "folding into a single result" are very common operations. The tool to do this in a single line is reduce.

02 / 05

Taking the accumulated value and the current item

The function passed to reduce receives two arguments.

The first is the total accumulated so far, and the second is the current element. Returning the new total from inside the function passes it forward as the first argument in the next round.

const nums = [1, 2, 3];const add = (total, n) => {  return total + n;};console.log(nums.reduce(add, 0));

Result

6

03 / 05

How the calculation advances

Let us see how nums.reduce(add, 0) works under the hood:

  • Start: total is 0, n is 1 -> returns 0 + 1 = 1
  • 2nd round: total is 1, n is 2 -> returns 1 + 2 = 3
  • 3rd round: total is 3, n is 3 -> returns 3 + 3 = 6

The final computed value becomes the return value of reduce as a whole.

04 / 05

Summing from objects

It shines when calculating the total price of item lists.

Set the initial value to 0 and return total + item.price, and you get the total sum in one line no matter how many items there are.

const items = [  { name: "pen", price: 100 },  { name: "notebook", price: 200 },];const sumPrice = (total, item) => {  return total + item.price;};console.log(items.reduce(sumPrice, 0));

Result

300

05 / 05

Check the key points

Let us review the ideas:

  • array.reduce(fn, initial) folds elements into a single value
  • The callback takes (accumulator, currentItem) => nextValue
  • The returned value is handed over to the next round

Let us practice using reduce!