Array reduce() Method
The Array reduce()
method returns a single value after iterating through each element of the given array inside the user-supplied callback function, where some calculation is performed on the preceding element. The syntax for this method is
array.reduce(callback(accumulator, currentValue), initialValue)
The callback()
function has two arguments as follows:
accumulator
The value returned in the previous call to the
callback()
function. Initially, it holds the second parameter initialValue
if it is passed, else, it takes the value array[0]
.
currentValue
Index of the current element in the array.
The second parameter initialValue
(optional) is the value passed to the callback()
on first call.
In this simple example below, we will join the words in the given array and create a full sentence.
let arr = ["I", "am", "worried", "about", "Gort"];
let say = arr.reduce((acc, i) => acc + " " + i);
console.log(say); // I am worried about Gort
Now we pass a string "Klaatu:
" as the initialValue
, which makes the value of the accumulator
initially.
let arr = ["I", "am", "worried", "about", "Gort"];
let say = arr.reduce((acc, i) => acc + " " + i, "Klaatu: ");
console.log(say); // Klaatu: I am worried about Gort