例如,我正在尝试对字符串数组进行排序:
array1 = ["BG", "UM", "BT", "FT", "PH", "FK"]
array2 = ["BG", "UM", "PH", "FK", "BT", "FT"]
我希望它始终保持此顺序:
["FT", "FK", "BT", "BG", "PH", "UM"]
如何使用JavaScript方法Sort对此进行排序?
您可以按照对象的所需顺序来获取对象,并按其所需顺序对值进行排序。
const
order = { FT: 1, FK: 2, BT: 3, BG: 4, PH: 5, UM: 6 },
getValue = key => order[key],
sort = (a, b) => getValue(a) - getValue(b),
array1 = ["BG", "UM", "BT", "FT", "PH", "FK"]
array2 = ["BG", "UM", "PH", "FK", "BT", "FT"]
console.log(...array1.sort(sort));
console.log(...array2.sort(sort));
如果没有重复,您可以过滤一个数组以获取更新的顺序
array1 = ["BG", "UM", "BT", "FT", "PH", "FK"]
array2 = ["BG", "UM", "PH", "FK", "BT", "FT"]
array3 = ["BG", "UM", "PH"]
var order = ["FT", "FK", "BT", "BG", "PH", "UM"]
function orderIt(arr) {
return order.filter(function(k){return arr.includes(k)})
}
console.log(orderIt(array1))
console.log(orderIt(array2))
console.log(orderIt(array3))
或者您可以排序
array1 = ["BG", "UM", "BT", "FT", "PH", "FK"]
array2 = ["BG", "UM", "PH", "FK", "BT", "FT"]
array3 = ["BG", "UM", "PH", "BG", "UM", "PH"]
var order = ["FT", "FK", "BT", "BG", "PH", "UM"].reduce(
function(o, k, i) {
o[k] = i;
return o;
},
{})
function orderIt(arr) {
return arr.sort(function(a, b) {
return order[a] - order[b];
})
}
console.log(orderIt(array1))
console.log(orderIt(array2))
console.log(orderIt(array3))