【问题标题】:Using array.reduce method to count duplicate elements [duplicate]使用 array.reduce 方法计算重复元素 [重复]
【发布时间】:2014-08-06 18:52:43
【问题描述】:

我正在完成一个关于函数式 JS 的教程,并且我遇到了一个需要使用 reduce 方法的挑战:

给定一个随机的单词数组,输出一个显示单词加上它的字数的数组,例如:['apple', 'orange', 'grape', 'apple'] -> ['apple: 2', 'orange: 1', 'grape: 1']

我知道这不是 reduce 的正确用法,但这是我的半工作解决方案:

var wordCountsArray = inputWords.map(function(item) {
    var counter = 0;
    var itemCount = inputWords.reduce(function(prevVal, curVal) {
        if (curVal == item) {
            counter++;
        }
        return;
    }, 0);

    return item + ": " + counter;
})

console.log(wordCountsArray);  

这确实输出了字数,但字数列表有重复,即看起来像:

['apple: 2', 'orange: 1', 'grape: 1', 'apple: 2']

而不是

['apple: 2', 'orange: 1', 'grape: 1']

我查阅了 MSDN 的方法指南、Mozilla 的几个博客。我知道它是如何作为累加器工作的,但是因为它使用上一次迭代的输出作为下一次迭代的输入,所以我不知道如何将它应用到这个任务中。我不需要解决方案,但也许对理解有一点帮助?

【问题讨论】:

  • 结果应该是一个对象,所以将其设置为累加器,然后查看给定的单词是否存在于对象上。如果不是,则将其分配给值为1 的对象,否则只需增加现有值。只要确保在每次迭代时都返回对象。它也将成为最终值。根本不需要.map()
  • 你需要给 reduce 的第二个参数一个对象。如果它做你想要的,就没有错误使用reduce。
  • @david ,抱歉重复。我尝试使用“array reduce,reduce method javascript”等查询搜索和查看其他问题,我如何更好地找到重复项?
  • 我真的不确定,但我(从记忆中)搜索了“javascript count word frequency stackoverflow”,这似乎有效。
  • 哦,我什至做出了回答!

标签: javascript arrays reduce


【解决方案1】:

我知道这是一个解决方案,但有时解决方案是最好的解释。跟随第一个块中的“fruitsCount”对象。注意“fruitsArray”只是这个对象的翻译,所以应该很容易理解。

var fruits = ['apple', 'orange', 'grape', 'apple'].reduce(function(fruitsCount, currentFruit){
    if(typeof fruitsCount[currentFruit] !== "undefined"){
      fruitsCount[currentFruit]++; 
      return fruitsCount;
    } else {
        fruitsCount[currentFruit]=1; 
        return fruitsCount;
    }
}, {});

var fruitsArray = [];
for(var x in fruits){
    fruitsArray.push(x + ": " + fruits[x]);
}

console.log(fruitsArray);

【讨论】:

  • fruitsCount[currentFruit] = (fruitsCount[currentFruit] || 0) + 1
  • PS:你错过了x变量声明。
猜你喜欢
  • 2023-03-11
  • 2017-02-28
  • 2013-02-13
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 2012-05-06
  • 2016-08-05
相关资源
最近更新 更多