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 fromcallback
in a previous iterationel
- current iteration elementindex
- index of a current elementarr
- array which reduce was executed on
initialValue
- value which will be passed tocallback
as anacc
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'}