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;
}
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.
push() The push() method adds one or more elements to the end of an array and returns the new length of the array.
push() adds at end; pop() deletes from end.
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.
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 }, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With