【问题标题】:search an array for duplicates, javascript [duplicate]在数组中搜索重复项,javascript [重复]
【发布时间】:2016-03-01 22:38:10
【问题描述】:

好的,我正在尝试搜索一个数组并找到重复项并返回每个重复项出现的次数。到目前为止,我需要传入两个参数,首先是要搜索的数组,然后是该数组中的特定术语:

countMatchingElements = function(arr, searchTerm){
var count = 0;
for(i = 0; i <= arr.length; i++){
count++;
}
return count;
};

我要搜索的数组:

var arrayToSearch = ['apple','orange','pear','orange','orange','pear'];

【问题讨论】:

    标签: javascript arrays loops for-loop


    【解决方案1】:
    var arrayToSearch = ['apple', 'orange', 'pear', 'orange', 'orange', 'pear'];
    
    var counter = {};
    
    arrayToSearch.forEach(function(e) {
        if (!counter[e]) {
            counter[e] = 1;
        } else {
            counter[e] += 1
        }
    });
    
    console.log(counter); //{ apple: 1, orange: 3, pear: 2 }
    

    【讨论】:

    • 这将适用于原始问题。请注意,如果您正在寻找重复的对象/数组,它将无法正常工作。
    • @MikeC 当然可以,谢谢
    【解决方案2】:

    这样的事情可能会奏效:

    var arrayToSearch = ['apple', 'orange', 'pear', 'orange', 'orange', 'pear'];
    
    countMatchingElements = function(arr, searchTerm) {
      return arr.filter(function(item) { return item === searchTerm; }).length;
    };
    
    document.writeln('"orange" appears ' + countMatchingElements(arrayToSearch, 'orange') + ' times.');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 2019-02-19
      • 2013-01-25
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多