[英]How do you sort an array of objects properly?
我似乎在讓一組對象正確排序方面遇到一個小問題。
例如,假設我有以下內容:
var items = [
{id: '1', itn: '1'},
{id: '2', itn: '10P'},
{id: '3', itn: '2'},
{id: '4', itn: '3'}
];
我需要根據“ itn”中的值對該數組進行排序。 但是,當我運行下面的函數時,將其列出為1、10P,2、3,而不是1、2、3、10P。
userData.sort(function (a, b) {
return (b.itn > a.itn) ? -1 : (b.itn < a.itn) ? 1 : 0;
});
我對如何進行此操作有些困惑,也不確定要搜索哪種關鍵字以獲得正確的指導。 任何幫助表示贊賞!
提前致謝。
似乎您正在嘗試根據itn
存在的整數部分對數組進行排序。 為此,您可以使用parseInt()
將項目( itn
)轉換為整數,然后比較這些整數值:
var userData = [ {id: '1', itn: '1'}, {id: '1', itn: '10P'}, {id: '1', itn: '2'}, {id: '1', itn: '3'} ]; var res = userData.sort(function (a, b) { a = parseInt(a.itn); b = parseInt(b.itn); return (b > a) ? -1 : (b < a) ? 1 : 0; }); console.log(res)
您可以將string#localeCompare
的numeric
屬性設為true
。
var items = [{id: '1', itn: '1'},{id: '1', itn: '10P'},{id: '1', itn: '2'},{id: '1', itn: '3'}]; items.sort((a,b) => a.itn.localeCompare(b.itn, undefined, {numeric: true})); console.log(items);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.