2 回答

TA貢獻1802條經驗 獲得超5個贊
split
每個value
at/(?=[A-Z])/
以獲得其垂直和水平位置。這將創建一個像這樣的數組:["upper", "Right"]
解構數組,將它們變成 2 個獨立的變量
創建 2 個優先對象。一個用于映射垂直位置的順序,另一個用于映射水平位置的順序
首先
sort
根據vertical
優先級。如果它們具有相同的優先級,vertical[a1] - vertical[b1]
將返回 0。因此,||
將根據horizontal
部分對它們進行排序
const array=[{value:"upperRight"},{value:"upperLeft"},{value:"bottomRight"},{value:"bottomCenter"},{value:"bottomLeft"}];
const vertical = {
"upper": 1,
"bottom": 2
}
const horizontal = {
"Left": 1,
"Center": 2,
"Right": 3
}
array.sort((a,b) => {
const [a1, a2] = a.value.split(/(?=[A-Z])/)
const [b1, b2] = b.value.split(/(?=[A-Z])/)
return vertical[a1] - vertical[b1] || horizontal[a2] - horizontal[b2]
})
console.log(array)
如果split
操作成本較高,您可以添加一個map
操作來預先獲取所有拆分值并對它們進行排序。

TA貢獻1900條經驗 獲得超5個贊
Array.prototype.sort() 允許您指定比較函數。只需設置一些關于如何對弦樂進行評分的基本規則即可。例如:
“上”值10分
“底部”得0分
“左”得2分
“中心”得1分
“正確”得0分。
在比較函數中將兩個分數相減,并將結果用作返回值。
var objects = [
{ value: 'upperRight' },
{ value: 'upperLeft' },
{ value: 'bottomRight' },
{ value: 'bottomCenter' },
{ value: 'bottomLeft' }
];
function scoreString(s) {
var score = 0;
if (s.indexOf('upper') > -1) score += 20;
if (s.indexOf('Left') > -1) score += 2;
else if (s.indexOf('Center') > -1) score += 1;
return score;
}
var sorted = objects.sort(function (a, b) {
return scoreString(b.value) - scoreString(a.value);
});
console.log(sorted);
添加回答
舉報