Skip to content

How to count occurrences of strings in array of arrays?

I have the following array of arrays (pasted below) and would like to loop through it to count how many times each color appears. What’s the simplest way to go about doing this?

[
["Brown"],
["Blue", "Green"],
["Red", "Black", "White", "Other"],
["Green"],
["Green", "Gold"],
["Blue"]
];

Answer

Use flat() and reduce():

const data = [
  ["Brown"],
  ["Blue", "Green"],
  ["Red", "Black", "White", "Other"],
  ["Green"],
  ["Green", "Gold"],
  ["Blue"]
];

const result = data.flat().reduce((a, v) => (a[v] = (a[v] || 0) + 1, a), {});

console.log(result);