給定陣列:
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": "..."
}
]
uj5u.com熱心網友回復:
如果您愿意用 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;
}
uj5u.com熱心網友回復:
您可以根據所需的順序創建一個帶有索引的物件,然后使用該函式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; }
uj5u.com熱心網友回復:
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]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/312303.html
標籤:javascript 数组 排序 目的
下一篇:熊貓用數字字串對列進行排序
