Steve Steve - 4 months ago 11
Javascript Question

array.prototype.reduce: Pushing string value to empty array within arrow function

I have the following code that reduces the array to numbers without the letter 'e'

var numbers = ["one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven"];
var reduced = numbers.reduce(function(reducedArray, number) {
if (number.toString().indexOf("e") === -1) {
reducedArray.push(number);
}
return reducedArray;
}, []);


Everything is working fine. But now i want the same code in an arrow-function

var reduced = numbers.reduce((reducedArray, number) => {
if (number.indexOf('e') === -1) {
reducedArray.push(number);
}
}, []);


But this doesn't work, because the
reducedArray
is undefined and I couldn't find any solution to this.

Answer

Your code does not work because you don't return the array. But you should use filter instead:

var numbers = ["one", "two", "three", "four", "five", "six",
               "seven", "eight", "nine", "ten", "eleven"];
var reduced = numbers.filter(number => !number.includes("e"));
console.log(reduced);