2 回答

TA貢獻(xiàn)1796條經(jīng)驗 獲得超7個贊
在原始數(shù)組上使用過濾器,為了排序順序,我使用了 COLORS 數(shù)組。我在最后添加了顏色“黃色”,因為它在排序標(biāo)準(zhǔn)中沒有提到,您可以根據(jù)自己的選擇進(jìn)行處理。
擴(kuò)展:
正如所希望的那樣,黃色現(xiàn)在介于橙色和黃色之間。
如果它是綠色的并且評論不是“看起來不錯”那么它應(yīng)該出現(xiàn)在開頭。
let list = [{
name: 'name1',
team: 'team1',
statuses: [{ time: 'day1', color: 'green', message: 'looks good'}, { time: 'day2', color: 'green', message: 'looks good'}]
},
{
name: 'name2',
team: 'team2',
statuses: [{ time: 'day1', color: 'yellow', message: 'mild concern'}, { time: 'day2', color: 'red', message: 'critical issue'}]
},
{
name: 'name3',
team: 'team3',
statuses: [{ time: 'day1', color: 'orange', message: 'mild concern'}, { time: 'day2', color: 'orange', message: 'potential issue'}]
},
{
name: 'name4',
team: 'team4',
statuses: [{ time: 'day1', color: 'yellow', message: 'mild concern'}, { time: 'day2', color: 'green', 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);

TA貢獻(xiàn)1895條經(jīng)驗 獲得超7個贊
您可以創(chuàng)建一個對象,在其中定義顏色順序,然后使用sort首先按顏色排序的方法,如果顏色相同,則按名稱排序
const data = [{"name":"name1","team":"team1","statuses":[{"time":"day1","color":"green","message":"looks good"},{"time":"day2","color":"green","message":"looks good"}]},{"name":"name2","team":"team2","statuses":[{"time":"day1","color":"yellow","message":"mild concern"},{"time":"day2","color":"red","message":"critical issue"}]},{"name":"name3","team":"team3","statuses":[{"time":"day1","color":"orange","message":"mild concern"},{"time":"day2","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)
添加回答
舉報