group and count objects of array and create new array [duplicate]

断了今生、忘了曾经 提交于 2019-12-11 14:40:43

问题


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: "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" } ]

The dynamic array can have to up to many different types but I have only 3 colors to use in my dashboard (ok, warning, critical). Its not a problem if the color is used multiple times!

I would like to create a new array for my dashboard to group and count my response and merge it with the colors to get the following result:

[{ name: "new", value: 2, color: 'ok' }, { name: "old", value: 1, color: 'warning' }, { name: "broken", value: 1, color: 'critical' }, { name: "used", value: 2, color: 'ok' }]

So, first of all I need to group them, count the objects in the groups, select an color and then create a new array.

(Note: I would not like to use extra javascript libraries like LINQ.js )

Could yo help me please?


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


来源:https://stackoverflow.com/questions/50913026/group-and-count-objects-of-array-and-create-new-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!