How to Count Items or Certain Items in JavaScript Array?

Count Items in Array

You can simply check length of array to count items in JavaScript array.

function CountItems(arr){
  return arr.length;
}

Count Certain Item in Array

To count certain item in an Array you can make use of Array filter method to find item in Array.

function CountItems(arr, item=null){
  if(item == null) return arr.length;
  let filteredResult = arr.filter(i => i == item);
  return filteredResult.length;
}

Count Certain Items in Array

Now what if you want to find a list of items in an Array. In that case, you need to iterate through certain items list and filter from the main array list and get the count. Here is the implementation:

function CountItems(arr, item=null){
  if(item == null) return arr.length;
  if(Array.isArray(item)) return countMultipleItems(arr, item);
  return countSingleItem(arr, item);
}

function countMultipleItems(arr, items){
  return items.map(item => {
    return {[item]:arr.filter(i => i == item).length}
  })
}

function countSingleItem(arr,item){
  let filteredResult = arr.filter(i => i == item);
  return filteredResult.length;
}

console.log(CountItems([1,2,3,4,2,3,4],[2,3]));
// Outputs:
-   [{ 2: 2 }, { 3: 2 }]
console.log(CountItems([1,2,3,4,2,3,4],2));
// Outputs:
- 2
console.log(CountItems([1,2,3,4,2,3,4],1));
// Outputs:
- 1