问题描述
我具有以下结构的对象列表,这些对象已经在顶层按名称属性进行了排序。
[{
name: 'name1'
team: 'team1'
statuses: [{ time: 'day1',color: 'green',message: 'looks good'},{ time: 'day2',message: 'looks good'}]
},{
name: 'name2'
team: 'team2'
statuses: [{ time: 'day1',color: 'yellow',message: 'mild concern'},color: 'red',message: 'critical issue'}]
},{
name: 'name3'
team: 'team3'
statuses: [{ time: 'day1',color: 'orange',message: 'potential issue'}]
}]
以上列表应根据状态列表中最后一个对象的颜色属性以自定义排序顺序(红色,橙色,绿色)进行排序。预期列表包含此顺序为team2,team3,team1的对象,如果存在多个相同颜色的对象,则应在顶层保留名称属性的排序。
我尝试通过以下方式使用reduce函数,并将它们全部组合在一起,但未获得预期的输出。
teams.reduce((r,t) => {
if(t.statuses[1].color === 'red');
r.push(t)
return r;
},{ [] })
teams.reduce((r,t) => {
if(t.statuses[1].color === 'orange');
r.push(t)
return r;
},{ [] })
teams.reduce((r,t) => {
if(t.statuses[1].color === 'green');
r.push(t)
return r;
},{ [] })
解决方法
在原始数组上使用过滤器,为了排序,我使用了COLORS数组。我在末尾添加了颜色“黄色”,因为排序标准中未提及它,您可以根据自己的选择进行处理。
扩展:
- 现在希望黄色是介于橙色和黄色之间的。
- 如果它是绿色,并且注释不是“看起来不错”,则应从头开始。
let list = [{
name: 'name1',team: 'team1',statuses: [{ time: 'day1',color: 'green',message: 'looks good'},{ time: 'day2',message: 'looks good'}]
},{
name: 'name2',team: 'team2',color: 'yellow',message: 'mild concern'},color: 'red',message: 'critical issue'}]
},{
name: 'name3',team: 'team3',color: 'orange',message: 'potential issue'}]
},{
name: 'name4',team: 'team4',message: 'potential issue'}]
}
];
const COLORS = ['red','orange','yellow','green'];
const GREEN = COLORS.indexOf('green');
let result = list.sort((a,b) => {
let stata = a.statuses[a.statuses.length-1];
let statb = b.statuses[b.statuses.length-1];
let cola = COLORS.indexOf(stata.color);
let colb = COLORS.indexOf(statb.color);
if (cola == GREEN && stata.message != 'looks good') {
return (colb == GREEN && statb.message != 'looks good') ? a.name.localeCompare(b.name) : -1;
}
if (colb == GREEN && statb.message != 'looks good') {
return 1;
}
return (cola < colb) ? -1 : ((cola > colb) ? 1: a.name.localeCompare(b.name));
});
console.log(result);
,
您可以创建一个对象,在其中定义颜色的顺序,然后使用sort
方法,首先按颜色排序,如果颜色相同,则按名称排序
const data = [{"name":"name1","team":"team1","statuses":[{"time":"day1","color":"green","message":"looks good"},{"time":"day2","message":"looks good"}]},{"name":"name2","team":"team2","color":"yellow","message":"mild concern"},"color":"red","message":"critical issue"}]},{"name":"name3","team":"team3","color":"orange","message":"potential issue"}]}]
const order = {
red: 1,orange: 2,green: 3
}
data.sort((a,b) => {
const aColor = a.statuses.slice(-1)[0].color;
const bColor = b.statuses.slice(-1)[0].color;
return order[aColor] - order[bColor] || a.name.localeCompare(b.name)
})
console.log(data)