Why doesn\'t a.push(b)
work in my Array.reduce()? a=a.push(b)
where b
is a string, turns a
to an integer.?!
Please note that this structure you provide is not clear enough
I would use instead an array of objects each having a name and a frecuency
var frequencies = [{name : "mats", frecuency : 1},
{name : "john", frecuency: 3},
{name : "johan", frecuency: 2},
{name : "jacob", frecuency: 3}];
Then you can use a filter operation and map to get what you need
var max = Math.max.apply(Math, frequencies.map(function(o){return o.frecuency;}));
var maxElems = frequencies.filter(function(a){return a.frecuency == max}).map(function(a){return a.name;});
maxElems
will give you the names of the people with higher frecuency
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;
}, []);
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.
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 }, []);