push() won't work as expected in reduce()
Since push()
returns the new length of the array, you're assigning the length to a
. Instead of a conditional operator, use an if
statement.
var winner = objKeys.reduce((a, b) => { if (frequency[b] === highestVal) { a.push(b); } return a;}, []);
The push() returns the new length. You can use ES2015 spread syntax:
var winner = objKeys.reduce((a, b)=> { a = (frequency[b] === highestVal)? [...a, b] : a; return a}, []);
Building on the excellent answer by @Alexander Moiseyev.
You can avoid setting and mutating both variables a
and winner
by doing the following:
return objKeys.reduce((acc, val) => frequency[val] === highestVal ? [...acc, val] : acc,[])
note: for clarity I have explicitly declared the accumulator and value in this reduce method.