count.js 387 B

123456789101112131415161718
  1. export default function count(arr) {
  2. // Counts the number of times the items of an array appear (only on the top
  3. // level; it doesn't search through nested arrays!). Returns a map of
  4. // item -> count.
  5. const map = new Map()
  6. for (const item of arr) {
  7. if (map.has(item)) {
  8. map.set(item, map.get(item) + 1)
  9. } else {
  10. map.set(item, 1)
  11. }
  12. }
  13. return map
  14. }