好的,我正在尝试搜索数组并查找重复项并返回每个重复项发生的次数。这就是我到目前为止,我需要首先传递两个参数,然后是被搜索的数组,然后是该数组中的特定术语:
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'];
答案 0 :(得分: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 }
答案 1 :(得分:0)
这样的事情可能会起到作用:
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.');