9. What is reduce function?

Function reduce can be called on an array and it takes two args - callback and initialValue:

  • callback is a function, which accepts 4 args. It's executed as many times as many elements there is in an array.
    • acc - accumulator - it's a value returned from callback in a previous iteration
    • el - current iteration element
    • index - index of a current element
    • arr - array which reduce was executed on
  • initialValue - value which will be passed to callback as an acc in a first iteration

reduce returns value which was returned from last execution of callback.

It has lots and lots of usages and for example it can be useful for summing up elements:

const numbers = [2, 4, 6]; const sum = numbers.reduce((acc, el) => { return acc + el; }, 0); console.log(sum); // 12

...or modyfing structure from array to object

const objs = [ { id: "1", value: "first" }, { id: "2", value: "second" }, ]; const idKeyed = objs.reduce((acc, el) => { acc[el.id] = el.value; return acc; }, {}); console.log(idKeyed); // {1: 'first', 2: 'second'}
devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.