Sort an array according to a property which may be null

喜欢而已 提交于 2020-06-08 19:58:31

问题


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 ?


回答1:


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



回答2:


You can evaluate the use of lodash and do something like:

const 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 }
];

const orderedItems = lodash.orderBy(items, 'value');

I hope this helps you.



来源:https://stackoverflow.com/questions/62179940/sort-an-array-according-to-a-property-which-may-be-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!