假設我有一個物件陣列:
Objects = [
{ "id": 1, "name": Joseph, function: "preacher"},
{ "id": 2, "name": Ann, function: "singer"},
{ "id": 3, "name": Miles, function: "preacher"},
{ "id": 4, "name": Jack, function: "singer"},
{ "id": 5, "name": Igor, function: "secretary"}
];
還有一系列屬性:
sort = ['function', 'name'];
我必須使用屬性組合(排序陣列)對物件陣列進行排序。所以我是這樣做的:
const intlCollator = new Intl.Collator('pt-BR', { usage: 'sort' });
Objects.sort(
(x, y) =>
(intlCollator.compare(x[sort[0]], y[sort[0]])) ||
(intlCollator.compare(x[sort[1]], y[sort[1]])) ||
(intlCollator.compare(x[sort[2]], y[sort[2]]))
);
我將如何使排序動態?我的意思是,使用可變排序組合進行迭代。例如:
sort = ['function', 'name'];
或者:
sort = ['name'];
uj5u.com熱心網友回復:
您可以迭代鍵,直到比較回傳一個不假的值。
const
objects = [{ id: 1, name: "Joseph", function: "preacher" }, { id: 2, name: "Ann", function: "singer" }, { id: 3, name: "Miles", function: "preacher" }, { id: 4, name: "Jack", function: "singer" }, { id: 5, name: "Igor", function: "secretary" }],
intlCollator = new Intl.Collator('pt-BR', { usage: 'sort' }),
sort = ['function', 'name'];
objects.sort((a, b) => {
let r;
sort.some(k => r = intlCollator.compare(a[k], b[k]));
return r;
});
console.log(objects);
uj5u.com熱心網友回復:
由于 ES10排序是穩定的。這意味著您可以先使用第一個鍵進行排序,然后對第二個鍵進行排序,依此類推。
const Objects = [
{ "id": 1, "name": "Joseph", function: "preacher"},
{ "id": 2, "name": "Ann", function: "singer"},
{ "id": 3, "name": "Miles", function: "preacher"},
{ "id": 4, "name": "Jack", function: "singer"},
{ "id": 5, "name": "Igor", function: "secretary"}
];
const sort = ['name', 'function'];
const intlCollator = new Intl.Collator('pt-BR', { usage: 'sort' });
sort.forEach(s => {
Objects.sort((l, r) => intlCollator.compare(l[s], r[s]));
});
console.log(Objects);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/376393.html
標籤:javascript 有角的 打字稿
下一篇:為什么我的排序實作不起作用?
