let data = [{chain:"jjj",num:222},{chain:"ERC20",num:333},{chain:"dyh",num:11},{chain:"OKTC",num:555},{chain:"USDT",num:222}]data.sort((a, b) => {// 期望的顺序; 此数组中不存在的交易对会被排序到末尾const sortIndex = ['USDT', 'ERC20', 'OKTC'].reverse()let aIndex = sortIndex.indexOf(a.chain)let bIndex = sortIndex.indexOf(b.chain)return bIndex - aIndex})console.log(data)//Array [Object { chain: "USDT", num: 222 }, Object { chain: "ERC20", num: 333 }, Object { chain: "OKTC", num: 555 }, Object { chain: "jjj", num: 222 }, Object { chain: "dyh", num: 11 }]
data.sort((a, b) => {
// 期望的顺序; 此数组中不存在的交易对会被排序到末尾
const sortIndex = ['USDT', 'ERC20', 'OKTC'].reverse()
let aIndex = sortIndex.indexOf(a.chain)
let bIndex = sortIndex.indexOf(b.chain)
return bIndex - aIndex
})
//Array [Object { chain: "USDT", num: 222 }, Object { chain: "ERC20", num: 333 }, Object { chain: "OKTC", num: 555 }, Object { chain: "jjj", num: 222 }, Object { chain: "dyh", num: 11 }]
给定排序数组实现按需求排序
const exchangeOrder = ['OKX', 'BINANCE', 'BITGET'];
const exchangesData = ["BITGET", "OKX", "BINANCE"];// 根据指定的顺序进行排序
const sortedExchangesData = exchangesData.sort((a, b) => {return exchangeOrder.indexOf(a) - exchangeOrder.indexOf(b);
});console.log(sortedExchangesData);// ['OKX', 'BINANCE', 'BITGET']