Skip to content Skip to sidebar Skip to footer

Push() Won't Work As Expected In Reduce()

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.?! getHighestValuesInFrequency: function(frequency) { //Input:var frequenc

Solution 1:

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;
}, []);

Solution 2:

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
}, []);

Solution 3:

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.

Solution 4:

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

varfrequencies= [{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

Solution 5:

The spread syntax enables an even shorter way:

const winner = objKeys.reduce((a, b) => {
  return frequency[b] === highestVal ? [...a, b] : a 
}, [])

Post a Comment for "Push() Won't Work As Expected In Reduce()"