簡體   English   中英

如何使用 javascript 中的兩個鍵對對象數組進行排序

[英]How to sort an array of objects with two keys in javascript

我有一個對象數組,我想根據兩個鍵對它進行排序。

var data = [{COMPONENT: 'PM-ABC', PRIORITY: '0.35'},
            {COMPONENT: 'PM', PRIORITY: '0.35'}
            {COMPONENT: 'PM', PRIORITY: ''}]

它應該首先對關鍵組件(升序)進行排序,然后對優先級進行排序(''應該在數字之前說'0.35')

我試過下面的代碼,它只根據鍵進行排序,即 COMPONENT

data.sort(function (a, b) {
            return (a['COMPONENT'] > b['COMPONENT']) ? 1 : (a['COMPONENT'] < b['COMPONENT']) ? -1 : 0;
        });

我期待以下結果

data = [{COMPONENT: 'PM', PRIORITY: ''}
        {COMPONENT: 'PM', PRIORITY: '0.35'}
        {COMPONENT: 'PM-ABC', PRIORITY: '0.35'}]

以最基本的方式,無需預先根據某些查詢執行排序策略,您可以只進行排序回調,首先考慮屬性COMPONENT ,當它們不同時,然后是屬性PRIORITY ,最后只有相等性返回零.

關鍵是,如果COMPONENT沒有差異,則前兩個標准通過,第三個成為下一個屬性比較。

 var data = [ {COMPONENT: 'PM-ABC', PRIORITY: '0.35'}, {COMPONENT: 'PM', PRIORITY: '0.35'}, {COMPONENT: 'PM', PRIORITY: ''} ] data.sort(function(a, b) { if (a.COMPONENT < b.COMPONENT) { return -1; } if (a.COMPONENT > b.COMPONENT) { return 1; } if (a.PRIORITY < b.PRIORITY) { return -1; } if (a.PRIORITY > b.PRIORITY) { return 1; } return 0; }); console.log(data);

您可以使用String#localeCompare

 let data = [{COMPONENT: 'PM-ABC', PRIORITY: '0.35'}, {COMPONENT: 'PM', PRIORITY: '0.35'}, {COMPONENT: 'PM', PRIORITY: ''}]; data.sort((a,b) => a.COMPONENT.localeCompare(b.COMPONENT) || a.PRIORITY.localeCompare(b.PRIORITY)); console.log(data);

您可以按階段排序,首先是COMPONENT ,然后是PRIORITY並勾選。

 const data = [{ COMPONENT: 'PM-ABC', PRIORITY: '0.35' }, { COMPONENT: 'PM', PRIORITY: '0.35' }, { COMPONENT: 'PM', PRIORITY: '' }]; data.sort((a, b) => a.COMPONENT.localeCompare(b.COMPONENT) || (b.PRIORITY === '') - (a.PRIORITY === '') ); console.log(data);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

假設PRIORITY應該是一個數字並且空字符串''0相同,您的解決方案是:

const data = [{ COMPONENT: 'PM-ABC', PRIORITY: '0.35' }, { COMPONENT: 'PM', PRIORITY: '0.35' }, { COMPONENT: 'PM', PRIORITY: '' }];

data.sort((a, b) => 
    a.COMPONENT.localeCompare(b.COMPONENT) ||
    ((parseFloat(a.PRIORITY) || 0) - (parseFloat(b.PRIORITY) || 0))
);

console.log(data);

暫無
暫無

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

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