Home > other >  I want to sort the string values of Object's Key in a given order. What would be the most optim
I want to sort the string values of Object's Key in a given order. What would be the most optim

Time:05-24

I want to sort "ONAIR", "READY", "CLOSING", "CLOSED" order in JavaScript. Is it possible string value of Object's key in map or sort of JavaScript?

as is :

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

to be:

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

CodePudding user response:

If I understand what you mean correctly. Try this:

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)

CodePudding user response:

One way to achieve this is with a dictionary which specifies the order you desire; then you can sort based on looking up the status values in that dictionary:

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)

  • Related