DEV Community

Osamuyi
Osamuyi

Posted on

Count Number of Times an Item Appears in an Array

JavaScript array methods are very powerful functions(methods) that have abstracted a lot of their functionalities. These methods help developers ease the manipulation of arrays to achieve the desired result.
check array methods for a list of some array methods in JavaScript.

For example; imagine you are working with the array below and are required to count the number of times each element in the array appears.

const data = [
  'car',
  'car',
  'truck',
  'truck',
  'bike', 'SUV', 'van','car',
  'walk',
  'car',
  'van',
  'bike',
  'walk',
  'car',
  'van',
  'car',
  'truck',
];
Enter fullscreen mode Exit fullscreen mode

A couple of array methods can be used to get the desired result.

Count the number of items using reduce() method

//set the result to a variable
let itemsObject = data.reduce((accumulator, item) => {
  if (accumulator[item]) {
    ++accumulator[item];
} else {
    accumulator[item] = 1;
}
return accumulator;
}, {})


//USING TENARY OPERATOR
let itemsObject = data.reduce((accumulator, item) => {
 return accumulator[item] ? ++accumulator[item] : (accumulator[item] = 1), accumulator
}, {})


console.log(itemsObject)
/*
 {
  bike: 2,
  car: 6,
  SUV: 1,
  truck: 3,
  van: 3,
  walk: 2
}
*/

Enter fullscreen mode Exit fullscreen mode

reduce() is a method that helps in getting the number of occurrences of each item in an array.

Count the number of items using for of loop

The for of loop is a modification of the for loop. It makes it easier to iterate through iterables such as arrays, maps, strings etc. It functions operates just like the forEach() method. The major difference between the for of loop and forEach() method is that, the for of loop is more compatible with async functions.

//initialize an empty object to store the items
let countVal = {};
for (val of data) {
  if (countVal[val]) {
    countVal[val] += 1;
  } else {
    countVal[val] = 1;
  }
}

console.log(countVal)
/*
 {
  bike: 2,
  car: 6,
  SUV: 1,
  truck: 3,
  van: 3,
  walk: 2
 }
*/
Enter fullscreen mode Exit fullscreen mode

Conclusion

Several other array methods can also be used to accomplish this task, however, if you need to count the number of items present in an array, using the for of loop is preferable because of its compatibility with async functions. The reduce() method is also a good option to use.

Top comments (0)