I’ve array of objects which i want to sort first on date i.e, ‘create_date_format’ in desc & if tie then sort on risk alphabetically i.e, asc
I tried lodash.orderBy(risk_list, [‘create_date_format’, ‘risk’], [‘desc’]) but as date is in string format it sorted on numbers in date string so for e.g 28 jan 2020 appears before 01 aug 2020 as 28 is higher than 01.
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" }]
I want to sort first on date i.e, ‘create_date_format’ in desc and if tie then on ‘risk’ alphabetically in asc
Advertisement
Answer
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) )