2

Okay I'm trying to search an array and find the duplicates and return the number of times each of the duplicates occurs. This is what I have so far, I need to pass in two arguments first the array being searched and then a specific term within that array:

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

Array I want to search:

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

2 Answers2

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 }
isvforall
  • 8,768
  • 6
  • 35
  • 50
0

Something like this might do the trick:

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.');
Nathan Friend
  • 12,155
  • 10
  • 75
  • 125