Skip to content Skip to sidebar Skip to footer

Group And Count Objects Of Array And Create New Array

I am using reactJS and have an dynamic array of object from an response which looks like the following: [{ year: 2016, origin: 'EN', type: 'new' }, { year: 2016, origin: 'EN', type

Solution 1:

You can use reduce to group the arrays into an object. Use Object.values to convert the object into an array.

You can define the colors on an object using the type as the key.

let arr = [{ year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "old" }, { year: 2016, origin: "EN", type: "used" }, { year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "broken" }, { year: 2016, origin: "EN", type: "used" } ]	
let colors = {'new' : 'ok', 'old' : 'warning', 'broken' : 'critical', 'used' : 'ok'}

let result = Object.values(arr.reduce((c, {type}) => {
  c[type] = c[type] || {name: type,value: 0,color: colors[type]};
  c[type].value++;
  return c;
}, {}))

console.log(result);

Choosing the colors randomly:

let arr = [{ year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "old" }, { year: 2016, origin: "EN", type: "used" }, { year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "broken" }, { year: 2016, origin: "EN", type: "used" } ]	
let colors = ['ok', 'warning', 'critical'];

let result = Object.values(arr.reduce((c, {type}) => {
  c[type] = c[type] || {name: type,value: 0,color: colors[Math.floor(Math.random() * colors.length)]};
  c[type].value++;
  return c;
}, {}))

console.log(result);

Post a Comment for "Group And Count Objects Of Array And Create New Array"