Count occurrences

OSCC · JavaScript, Array · Oct 18, 2020

Counts the occurrences of a value in an array.

  • Use Array.prototype.reduce() to increment a counter each time the specific value is encountered inside the array.
const countOccurrences = (arr, val) =>
  arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

Recommended snippets

  • Mutates the original array to filter out the values specified, based on a given iterator function.

  • JSON to CSV

    JavaScript, Array

    Converts an array of objects to a comma-separated values (CSV) string that contains only the columns specified.

  • Count grouped elements

    JavaScript, Array

    Groups the elements of an array based on the given function and returns the count of elements in each group.