Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 frequency = {mats: 1,john: 3,johan: 2,jacob: 3};
 //Output should become ['John','jacob']

var objKeys = Object.keys(frequency);
var highestVal = objKeys.reduce((a,b)=>
            {highestVal = (frequency[b] > a)? frequency[b] : a;
             return highestVal;},0);

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

return winner;  
 }                                  
like image 778
Lasse Karagiannis Avatar asked Sep 22 '15 16:09

Lasse Karagiannis


People also ask

Can push () be used on string?

Pushing on a string is a figure of speech for influence that is more effective in moving things in one direction rather than another—you can pull, but not push.

What does array push () do?

push() The push() method adds one or more elements to the end of an array and returns the new length of the array.

What is the opposite of push () in JavaScript?

push() adds at end; pop() deletes from end.

How do you push an element to an array?

JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.


2 Answers

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;
}, []);
like image 126
Barmar Avatar answered Oct 11 '22 17:10

Barmar


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

like image 20
Alexander Moiseyev Avatar answered Oct 11 '22 19:10

Alexander Moiseyev