Hi,
given an array of words. With reduce I want to add the lengths of all words.
function calculateLength(items) {
let totalLength = 0;
let itemLength = [];
items.map(e => itemLength.push(e.length));
totalLength = itemLength.reduce(e => e + e);
return totalLength;
}
calculateLength(["dog", "donkey", "cat"]); //12
Is there a way to get rid of the map method to use just reduce? If I do so without pushing the lengths of items into a new array (itemLength), I got NaN.
Sometimes you can remove the comma zero from the reduce too, but that’s only when the first item can be automatically used as the initial value, which isn’t the case here.
I think that I prefer that instead, but the decision can be different depending on the code. What’s important is to explore some of the different ways to do things, for that’s when you can compare and contrast.
Hi @Paul_Wilkins many thanks for the clarification. Especially the part with “comma 0” I found interesting. I will get accustomed to, to always user “comma 0” at the end (inital value) to reduce (no pun intended) error messages with empty-arrays.
Comma zero shouldn’t always be used. That’s only used in this example as 0 is that starting value for the count that we’re doing.
Sometimes comma array is used instead for example, when you want to start with an empty array, and other times it’s something else different yet again, depending on what your initial state should be.