Home > database >  sort keeping 2 items on top
sort keeping 2 items on top

Time:06-15

I have an array object like

const d = [
    { id: 20, text: 'deaf' },
    { id: 30, text: 'acta', },
    { id: 0, text: 'deema1' },
    { id: -1, text: 'deema2' },
]

I want to sort the array by text but want to keep id -1 and 0 always on top, so the result would be

// sorted
[
    { id: -1, text: 'deema2' },
    { id: 0, text: 'deema2' },
    { id: 30, text: 'acta' },
    { id: 20, text: 'deaf' },
]

I tried to sort like d.sort((a, b) => (a.text).localeCompare(b.text)) but not sure how to handle case -1 and 0

const d = [
    { id: 20, text: 'deaf' },
    { id: 30, text: 'acta', },
    { id: 0, text: 'deema1' },
    { id: -1, text: 'deema2' },
];

d.sort((a, b) => (a.text).localeCompare(b.text))

console.log(d);

CodePudding user response:

You can put multiple conditions inside of sort to get the desired result. The first condition being more important than the next and so on.

const d = [{
    id: 20,
    text: 'deaf'
  },
  {
    id: 30,
    text: 'acta',
  },
  {
    id: 0,
    text: 'deema1'
  },
  {
    id: -1,
    text: 'deema2'
  },
]

const sorted = d.sort((a, b) => {
  if (a.id === -1) {
    return -1;
  }
  if (a.id === 0) {
    return -1;
  }
  return a.text.localeCompare(b.text);
});

console.log(sorted)

CodePudding user response:

You can work with indexOf:

const d = [
    { id: 20, text: 'deaf' },
    { id: 30, text: 'acta', },
    { id: 0, text: 'deema1' },
    { id: -1, text: 'deema2' },
    { id: 0, text: 'ace' },
    { id: -999, text: 'hello' },
    { id: 800, text: 'game' },
]

d.sort((a, b) => [0,-1].indexOf(b.id) - [0,-1].indexOf(a.id) 
                 || a.text.localeCompare(b.text));

console.log(d);

This will order all objects with id -1 first, and among those, the text property will define the order, then all objects with id 0, (again relatively ordered by text) and finally all other objects by text.

In case you want there to be no distinction between 0 and -1, but sort all those by text among themselves, then use includes instead of indexOf:

const d = [
    { id: 20, text: 'deaf' },
    { id: 30, text: 'acta', },
    { id: 0, text: 'deema1' },
    { id: -1, text: 'deema2' },
    { id: 0, text: 'ace' },
    { id: -999, text: 'hello' },
    { id: 800, text: 'game' },
]

d.sort((a, b) => [0,-1].includes(b.id) - [0,-1].includes(a.id) 
                 || a.text.localeCompare(b.text));

console.log(d);

  • Related