Ucenna
Ucenna

Reputation: 177

Advanced usage of the `reduce` method

I just recently learned reduces 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.

Upvotes: 1

Views: 175

Answers (2)

ryan
ryan

Reputation: 1084

Do not use reduce in this case. Use the following:

miscArray.map(x => "\nYou have a "+ x +".").join("")

Upvotes: 3

zerkms
zerkms

Reputation: 254896

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.

Upvotes: 4

Related Questions