javascript - push() 不会在 reduce() 中按预期工作

标签 javascript arrays reduce

为什么 a.push(b) 在我的 Array.reduce() 中不起作用? a=a.push(b) 其中 b 是字符串,将 a 转换为整数。?!

 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;  
 }                                  

最佳答案

由于 push() 返回数组的新长度,您将长度分配给 a。使用 if 语句代替条件运算符。

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

关于javascript - push() 不会在 reduce() 中按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32722435/

相关文章:

javascript - 尝试了解如何使用 _.reduce

javascript - 我如何使用 .map()、.reduce() 和 .filter() 来代替 forEach 来使我的代码简洁以免脆弱?

javascript - 网站的 API 未定义

c++ - 传递数组的差异

java - 在 Java/继承中重用静态字符串数组,就像字符串数组中的概念一样

javascript - 如何提高 javascript 数组操作中嵌套循环的性能?

parsing - Bison 转移减少冲突,我不知道在哪里

javascript - 在 jQuery 或 Javascript 中获取某个属性的最高值和最低值

javascript - 如何使用 jquery 从左到右或从右到左为 2 个 css 布局设置动画?

javascript - $(this) 在 jQuery 中如何工作