我有一個物件陣列
let objs = [
{ name: 'Mark',
age: 30,
id: 3,
},
{ name: 'Anne',
age: 20,
id: 2,
},
{ name: 'James',
age: 40,
id: 4,
},
{ name: 'Jerry',
age: 30,
id: 1,
},
{ name: 'Lucy',
age: 30,
id: 5,
},
{ name: 'Mark',
age: 30,
id: 6,
},
]
例如,我有一個欄位陣列: ['name', 'age']; 欄位數是動態的。它可以是 2、1 或 3。如果它是靜態的,我會使用排序運算子 | | 像這樣:
objs.sort((a,b)=> (a.age - b.age || a.name.localeCompare(b.name)));
有任何想法嗎?
uj5u.com熱心網友回復:
您可以使用https://stackoverflow.com/a/22672370/3807365中的這個多重排序功能- 基本上,您只需告訴它要排序的欄位,您就會得到一個排序方法來傳遞給您的 Array.sort。
let objs = [{
name: 'Mark',
age: 31,
id: 3,
},
{
name: 'Anne',
age: 20,
id: 2,
},
{
name: 'James',
age: 40,
id: 4,
},
{
name: 'Jerry',
age: 30,
id: 1,
},
{
name: 'Lucy',
age: 30,
id: 5,
},
{
name: 'Mark',
age: 30,
id: 6,
},
]
function getSortMethod() {
var _args = Array.prototype.slice.call(arguments);
return function(a, b) {
for (var x in _args) {
var ax = a[_args[x].substring(1)];
var bx = b[_args[x].substring(1)];
var cx;
ax = typeof ax == "string" ? ax.toLowerCase() : ax / 1;
bx = typeof bx == "string" ? bx.toLowerCase() : bx / 1;
if (_args[x].substring(0, 1) == "-") {
cx = ax;
ax = bx;
bx = cx;
}
if (ax != bx) {
return ax < bx ? -1 : 1;
}
}
}
}
objs.sort(getSortMethod(' name', ' age'));
console.log(objs)
.as-console-wrapper {
max-height: 100% !important;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/504830.html
標籤:javascript 排序