Counting all array elements that match a condition

Want to know how many elements in an array match a condition? We can use this to count all elements in an array that return true for a function that checks this condition.

// takes an array and a function to check each element in the array against
const countBy = (array, checkFunction) => {
  return array.reduce((count, element) => {
    return checkFunction(element) ? count + 1 : count
  }, 0)
}

// we can count how many numbers in an array are smaller than a given limit
countBy([-4, 3, -7, 5, 0, -3, 1, -8], number => number < 0)
// ⇒ 4

// we can count how many strings are exactly four characters long
countBy(['John', 'Paul', 'George', 'Ringo'], name => name.length === 4)
// ⇒ 2

// we can also check if objects have a certain value in a property
countBy([
  {
    name: 'Bulbasaur',
    types: ['Grass', 'Poison']
  }, {
    name: 'Nidoqueen',
    types: ['Poison', 'Ground']
  }, {
    name: 'Abra',
    types: ['Psychic']
  }, {
    name: 'Tentacool',
    types: ['Water', 'Poison']
  }
], pokemon => pokemon.types.includes('Poison'))
// ⇒ 3

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.