[英]How to sort an array of objects by custom order given as a string or array?
給定數組:
var someAnswers = [
{
answer: 'Lyndon Johnson', // answer A
comment: '...'
},
{
answer: 'Richard Nixon', // answer B
comment: '...'
},
{
answer: 'Jimmy Carter', // answer C
comment: '...'
},
{
answer: 'Gerald Ford', // answer D
comment: '...'
}
];
一些自定義訂單:
customOrder = 'A, C, B, D';
或者
customOrder = ['A', 'C', 'B', 'D'];
做這樣的事情:
someAnswers.sort(customOrder);
想要的結果:
[
{
"answer": "Lyndon Johnson",
"comment": "..."
},
{
"answer": "Jimmy Carter",
"comment": "..."
},
{
"answer": "Richard Nixon",
"comment": "..."
},
{
"answer": "Gerald Ford",
"comment": "..."
}
]
另一個自定義訂單:
anotherCustomOrder = 'D, B, A, C';
或者
anotherCustomOrder = ['D', 'B', 'A', 'C'];
做這樣的事情:
someAnswers.sort(anotherCustomOrder);
想要的結果:
[
{
"answer": "Gerald Ford",
"comment": "..."
},
{
"answer": "Richard Nixon",
"comment": "..."
},
{
"answer": "Lyndon Johnson",
"comment": "..."
},
{
"answer": "Jimmy Carter",
"comment": "..."
}
]
const sorting = (currentArray, indexArr) => { const reArrangedArr = []; const deepCopied = JSON.parse(JSON.stringify(currentArray)); indexArr.forEach(index => reArrangedArr.push(deepCopied[index])); return reArrangedArr; } var someAnswers = [ { answer: 'Lyndon Johnson', // answer A comment: '...' }, { answer: 'Richard Nixon', // answer B comment: '...' }, { answer: 'Jimmy Carter', // answer C comment: '...' }, { answer: 'Gerald Ford', // answer D comment: '...' } ]; console.log(sorting(someAnswers, [3,0,1,2]))
如果您願意用 customOrder 中的數字替換字母,您可以執行以下操作:
customOrder = [0, 2, 1, 3];
sort(someAnswers, customOrder) {
res = [];
customOrder.forEach((n) => {
res.push(someAnswers[n]);
}
return res;
}
或者,如果您真的想使用字母:
customOrder = ["A", "C", "B", "D"];
sort(someAnswers, customOrder) {
res = [];
customOrder.forEach((n) => {
res.push(someAnswers[n.charCodeAt(0) - 65]);
}
return res;
}
您可以根據所需的順序創建一個帶有索引的對象,然后使用函數Array.prototype.map
並使用之前創建的索引數組提取值。
const someAnswers = [ { answer: 'Lyndon Johnson', comment: '...' }, { answer: 'Richard Nixon', comment: '...' }, { answer: 'Jimmy Carter', comment: '...' }, { answer: 'Gerald Ford', comment: '...' }], answerIndexes = ['A', 'B', 'C', 'D'].reduce((a, c, i) => ({...a, [c]: i}), {}), customOrder = ['A', 'C', 'B', 'D'], sorted = customOrder.map(L => someAnswers[answerIndexes[L]]); console.log(sorted);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.