Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Using Reduce to Count Item Frequency In Array #210

@thall1961

Description

@thall1961

Thanks for doing this, I've been intimidated to try this anywhere else.

From this Stack Overflow question

The function will count how many times an item occurs in an array, even in arrays within the array.

function reduceCount(array, itemToCount) {
  return array.reduce((a, b) => {
    if (Array.isArray(b)) {
      return a + reduceCount(b, itemToCount)
    }
    return a + (b === itemToCount ? 1 : 0)
  }, 0)
}

Sample usage and output:

const array = [1, [2, 3, 4], 4, [5, 6, 7], 4]
reduceCount(array, 4)

expected: 3

I'll also add some checks to make sure the array parameter is actually an array and that it has at least one value

// make sure the array passed in is actually an array
if (!Array.isArray(array)) {
  return "Array isn't an array."
}

// make sure we got something to work with in that array
if (array.length === 0) {
  return 'Array is empty.'
}

Let me know if this is acceptable.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions