eggheadio-github / stack-overflow-copy-paste

Utility functions copy/pasted (and modified slightly) from Stack Overflow
441 stars 606 forks source link

Using Reduce to Count Item Frequency In Array #210

Closed thall1961 closed 5 years ago

thall1961 commented 5 years ago

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!

kentcdodds commented 5 years ago

Sounds great! 💯

kentcdodds commented 5 years ago

Great job!