Ucenna Ucenna - 1 month ago 6
Javascript Question

Advanced usage of the `reduce` method

I just recently learned

reduce
s functionality. It's been extremely useful. Recently I used it on an array of strings to automatically produce a series of outputs for me. I want to turn something like:

miscArray = ["dog", "cat", "hamster"]


into something like:

miscString =
"\nYou have a dog.
\nYou have a cat.
\nYou have a hamster."


However, reduce doesn't apply it's function to the first iteration of an array. If my code looks something like this:

function outputString(x,y){
return x+"\nYou have a "+y+".";
}

miscArray = ["dog", "cat", "hamster"]

alert(miscArray.reduce(outputString));


I end up getting something like this:

"dog
\nYou have a cat.
\nYou have a hamster."


As a workaround, I've been using an empty string in the start of my array like so :
miscArrray = ["","dog", "cat", "hamster"]
. However, using a workaround just means that I don't know how to do things right. I'm considering just making my own variant of the
reduce()
method, but if there's a right/better way to do it. I'd rather do it that way.

Answer

There surely is:

you need to specify the initial value for the accumulator. In your case it is '' (an empty string).

function outputString(x,y){
  return x+"\nYou have a "+y+".";
}

miscArray = ["dog", "cat", "hamster"]

alert(miscArray.reduce(outputString, ''));

When the initial value for the accumulator is set it is passed as the first argument on the first iteration, together with the first array item as a second parameter, and so on.

It actually is a good habit to ALWAYS explicitly set the accumulator, since then the typing of the expression becomes much more obvious and clear.