-1

I have this array/object of JavaScript

[
  {
    "name": "A",
    "selected_color": "Red"
  },
  {
    "name": "B",
    "selected_color": "Green"
  },
  {
    "name": "C",
    "selected_color": "Blue"
  },
  {
    "name": "D",
    "selected_color": "Red"
  }
]

How can I convert it to following format?

[
  {
    "color": "Red",
    "count": "2"
  },
  {
    "color": "Green",
    "count": "1"
  },
  {
    "color": "Blue",
    "count": "1"
  }
]

I want to filter values based on 'selected_color' key, also 'count' will store how many time specific color was selected.

Megamind
  • 33
  • 5
  • 1
    use `.reduce`... – AdityaParab Jul 19 '22 at 12:09
  • Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask), and this [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). Code that you've worked on to solve the problem should include a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), and be included in your question. – Louys Patrice Bessette Jul 19 '22 at 12:11

2 Answers2

1

Use .reduce

const arr = [
  {
    "name": "A",
    "selected_color": "Red"
  },
  {
    "name": "B",
    "selected_color": "Green"
  },
  {
    "name": "C",
    "selected_color": "Blue"
  },
  {
    "name": "D",
    "selected_color": "Red"
  }
];

const op = arr.reduce((acc, cur) => {
  const {selected_color} = cur;
  const colorObj = acc.find(({color}) => color === selected_color );

  if(colorObj) {
    colorObj.count++;
  } else {
    acc.push({color: selected_color, count: 1});
  }

  return acc;
  
}, []);

console.log(op);
/*

[
  { color: 'Red', count: 2 },
  { color: 'Green', count: 1 },
  { color: 'Blue', count: 1 }
]

*/
AdityaParab
  • 7,024
  • 3
  • 27
  • 40
1

You can try this (using groupBy) :

let data = [
{
    "name": "A",
    "selected_color": "Red"
},
{
    "name": "B",
    "selected_color": "Green"
},
{
    "name": "C",
    "selected_color": "Blue"
},
{
    "name": "D",
    "selected_color": "Red"
}
];

let groupBy = (arr, key) => {
    return arr.reduce((rv, x) => {
        (rv[x[key]] = rv[x[key]] || []).push(x);
        return rv;
    }, {});
};

let groupedData = groupBy(data, "selected_color");
let result = Object.keys(groupedData).map(color => ({'color': color, 'count': groupedData[color].length}) );

console.log(result);
nem0z
  • 1,060
  • 1
  • 4
  • 17