问题
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