Count occurrences

JavaScript, Array · Oct 18, 2020

Counts the occurrences of a value in an array.

const countOccurrences = (arr, val) =>
  arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

More like this

  • JSON to CSV

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

    JavaScript, Array · Oct 13, 2021

  • Tip: Min and max value in a JavaScript array

    When working with numeric arrays in JavaScript, you might need to find the minimum or maximum value. Here's a quick and easy way to do it.

    JavaScript, Array · Nov 6, 2021

  • Pull values from array based on function

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

    JavaScript, Array · Oct 22, 2020