我想按给定顺序对对象键的字符串值进行排序。最优化的方法是什么?



我想排序"ONAIR", "READY", "CLOSING", "CLOSED"JavaScript中的顺序。它是可能的字符串值的对象的关键在地图或JavaScript类型?

原形:

const list = [
{status: 'READY'},
{status: 'CLOSED'},
{status: 'ONAIR'},
{status: 'CLOSING'},
];

:

const list = [
{status: 'ONAIR'},
{status: 'READY'},
{status: 'CLOSING'},
{status: 'CLOSED'},
];

如果我没理解错的话。试试这个:

const sortSequencely = ["ONAIR", "READY", "CLOSING", "CLOSED"];
const list = [
{status: 'READY'},
{status: 'CLOSED'},
{status: 'ONAIR'},
{status: 'CLOSING'},
];
console.log('Original list', list);
const listSorted = list.sort((a,b) => {
const indexA = sortSequencely.findIndex(x=>x === a.status);
const indexB = sortSequencely.findIndex(x=>x === b.status);
return indexA - indexB;
})
console.log('Sorted list', listSorted)

实现此目的的一种方法是使用字典指定所需的顺序;然后您可以根据查找字典中的status值进行排序:

const list = [
{status: 'READY'},
{status: 'CLOSED'},
{status: 'ONAIR'},
{status: 'CLOSING'},
];
const order = { 'ONAIR' : 0, 'READY' : 1, 'CLOSING' : 2, 'CLOSED' : 3 }
list.sort((a, b) => order[a.status] - order[b.status]);
console.log(list)

相关内容

  • 没有找到相关文章

最新更新