2

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"]
];

4 Answers 4

5

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);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Array.reduce().

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

const output = input.reduce((acc, cur) => {
  cur.forEach(item => {
    if (!acc[item]) acc[item] = 0;
    acc[item] ++;
  })
  return acc;
}, {})

console.log(output);

Comments

0

Use a counter to count and iterate through the array

let counter = {}
let colorAry = [
    ["Brown"],
    ["Blue", "Green"],
    ["Red", "Black", "White", "Other"],
    ["Green"],
    ["Green", "Gold"],
    ["Blue"]
];

for(let ary of colorAry) {
    for(let color of ary) {
        if(counter[color]==undefined) counter[color] = 0
        counter[color]++
    }
}
console.log(counter)

Comments

0

Loop each array and sub arrays and store the count in another variable.

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

// to store the count
let counter = {};

// loop each and sub sub arrays
data.forEach(item => {
  item.forEach(subItem => {
    counter[subItem] = counter[subItem] ? counter[subItem] + 1 : 1
  })
});

console.log(counter);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.