2 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個(gè)贊
let sorted = arr.sort((a, b) =>
// sort by create_date_format desc
(new Date(b.create_date_format) - new Date(a.create_date_format))
// if 0 (tie), sort by risk asc
|| a.risk.localeCompare(b.risk)
)

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以做的是編寫一個(gè)排序函數(shù),該函數(shù)具有用于比較屬性的簡(jiǎn)單檢查。為了首先按日期排序,您需要將字符串日期轉(zhuǎn)換為實(shí)例Date,以便按時(shí)間而不是按字符對(duì)值進(jìn)行排序。
為要比較的兩個(gè)對(duì)象創(chuàng)建日期實(shí)例后,您可以檢查兩個(gè)日期項(xiàng)是否相等。如果是,則跳過此排序邏輯并執(zhí)行基于 的排序risk。查看代碼片段
let arr = [{avoided: 0,
avoided_note: null,
create_date_format: "28 Sep 2020",
id: 209,
notes: "Nothing is happening",
risk: "very high risk",
severity: 3,
severity_name: "High",
type: 1,
type_name: "Internal"},
{ avoided: 0,
avoided_note: null,
create_date_format: "23 Sep 2020",
id: 206,
notes: null,
risk: "Risk 12",
severity: 3,
severity_name: "High",
type: 2,
type_name: "External"}, {avoided: 0,
avoided_note: null,
create_date_format: "22 Sep 2020",
id: 202,
notes: "test note",
risk: "test risk",
severity: 3,
severity_name: "High",
type: 2,
type_name: "External"},
{ avoided: 0,
avoided_note: null,
create_date_format: "23 Sep 2020",
id: 206,
notes: null,
risk: "abc Risk 12",
severity: 3,
severity_name: "High",
type: 2,
type_name: "External"}]
var sortedArr = arr.sort((a, b)=>{
var aDate = new Date(a.create_date_format)
var bDate = new Date(b.create_date_format)
if (aDate.getTime() === bDate.getTime()){
//for strings return 1 or -1 depending on condition
return b.risk > a.risk ? 1 : -1
} else {
return aDate - bDate
}
})
console.log(sortedArr)
添加回答
舉報(bào)