Search code examples
javascripttypescriptsortingecmascript-6ecmascript-5

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 ?


Solution

  • 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; }