Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array according to a property which may be null

I ve an array of objects :

let items = [
  { name: 'eric', value: 1 },
  { name: 'bob', value: 4 },
  { name: 'michael', value: 0 },
  { name: 'john', value: 3 },
  { name: 'brad', value: null },
  { name: 'martin', value: 2 },
  { name: 'chris', value: null }
];

i want to sort my array so that the objects can be sorted by the "value" attribute , and if it's null , make the object in the bottom of the array :

  { name: 'michael', value: 0 },
  { name: 'eric', value: 1 },
  { name: 'martin', value: 2 },
  { name: 'john', value: 3 },
  { name: 'bob', value: 4 },
  { name: 'brad', value: null },
  { name: 'chris', value: null }

->

i ve tried this ;

items.sort((a, b) => {
    return (a.orde ===null)-(b.ordre===null) || +(a.ordre>b.ordre)||-(a.ordre<b);
});

But seems that it's not working

Suggestions ?

like image 300
firasKoubaa Avatar asked Oct 15 '25 13:10

firasKoubaa


1 Answers

You could check for null first and then sort by the value.

let items = [{ name: 'eric', value: 1 }, { name: 'bob', value: 4 }, { name: 'michael', value: 0 }, { name: 'john', value: 3 }, { name: 'brad', value: null }, { name: 'martin', value: 2 }, { name: 'chris', value: null }];

items.sort(({ value: a }, { value: b }) => (a === null) - (b === null) || a - b);

console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 158
Nina Scholz Avatar answered Oct 17 '25 13:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!