Finding out how many times an array element appears

  • Keep a variable for the total count
  • Loop through the array and check if current value is the same as the one you’re looking for, if it is, increment the total count by one
  • After the loop, total count contains the number of times the number you were looking for is in the array

Show your code and we can help you figure out where it went wrong

Here’s a simple implementation (since you don’t have the code that didn’t work)

var list = [2, 1, 4, 2, 1, 1, 4, 5];  

function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    return count;
}

countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3

countInArray could also have been implemented as

function countInArray(array, what) {
    return array.filter(item => item == what).length;
}

More elegant, but maybe not as performant since it has to create a new array.

Leave a Comment