簡體   English   中英

如何以數字方式對具有多個參數的對象數組進行排序

[英]How to sort a object array with more than one argument numerically

我需要在我的 Web 應用程序中創建一個函數。 該函數接收一個 JS 對象作為參數,並從低到高返回組織好的列表。 該對象有兩個要分析的參數。

var medicines = [
  {type:"Glibenclamida 5 mg", hour1:2, hour2: 4},
  {type:"Noretisterona 0,35 mg", hour1:4, hour2: 8},
  {type:"Glibenclamida 99 mg", hour1:8, hour2: 16}
];

所以,這只是一個例子,我需要這些列表返回......

1: hour 2- Glibenclamida 5 mg
2: hour 4- Glibenclamida 5 mg, Noretisterona 0,35 mg
3: hour 8- Noretisterona 0,35 mg, Glibenclamida 99 mg
4: hour 16 - Glibenclamida 99 mg

這只是一個例子,我需要一個像這樣有組織的列表。

這可以使用reduce來解決,看看下面的解決方案。

 var medicines = [ {type:"Glibenclamida 5 mg", hour1:2, hour2: 4}, {type:"Noretisterona 0,35 mg", hour1:4, hour2: 8}, {type:"Glibenclamida 99 mg", hour1:8, hour2: 16} ]; var convertedMedicines = medicines.reduce((res, medicine) => { res[medicine.hour1] = res[medicine.hour1] || []; res[medicine.hour2] = res[medicine.hour2] || []; res[medicine.hour1].push(medicine.type); res[medicine.hour2].push(medicine.type); return res; }, {}); console.log(convertedMedicines)

這也可以通過 map 函數來完成。 映射對象數組,然后檢查類型的索引是否存在。 如果是,那么我們正常推送它,如果它不存在,那么我們用之前的值(iln -1)推送它。

 var medicines = [{ type: "Glibenclamida 5 mg", hour1: 2, hour2: 4 }, { type: "Noretisterona 0,35 mg", hour1: 4, hour2: 8 }, { type: "Glibenclamida 99 mg", hour1: 8, hour2: 16 } ]; let an = medicines.map((val, iln) => { if (!iln && medicines[iln + 1].type) { return { [iln + 1]: "hour" + val.hour1 + "-" + val.type } } else { return { [iln + 1]: "hour" + medicines[iln].hour1 + "-" + medicines[iln - 1].type + "," + medicines[iln].type } } }) an.push({[medicines.length + 1]: "hour" + medicines[medicines.length-1].hour2 + "-" + medicines[medicines.length-1].type}) console.log(JSON.stringify(an))

我們手動推送最后一個值,因為它沒有后繼,並且在 map 中執行它是無用的。

你得到的輸出為

[{
  "1": "hour2-Glibenclamida 5 mg"
}, {
  "2": "hour4-Glibenclamida 5 mg,Noretisterona 0,35 mg"
}, {
  "3": "hour8-Noretisterona 0,35 mg,Glibenclamida 99 mg"
}, {
  "4": "hour16-Glibenclamida 99 mg"
}]

改進馬里烏斯的減少

這不會對 hour1 和 hour2 進行硬編碼 - 以防有 hour3 等 - 因此使用以小時開頭的任何鍵

 var medicines = [ {type:"Glibenclamida 5 mg", hour1: 2, hour2: 4}, {type:"Noretisterona 0,35 mg", hour1: 4, hour2: 8, hour3: 16}, {type:"Glibenclamida 99 mg", hour1: 8, hour2: 16} ]; var convertedMedicines = medicines.reduce((res, medicine) => { Object.keys(medicine).forEach(key => { if (key.indexOf("hour")==0) { res["hour "+medicine[key]] = res["hour "+medicine[key]] || []; res["hour "+medicine[key]].push(medicine.type); } }); return res; }, {}); console.log(convertedMedicines)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM