Reputation: 43
My array of objects is as following.
let obj=[
{
id:1,
pinnedBy:"abc",
value:9
},
{
id:2,
pinnedBy:null,
value:10
},
{
id:3,
pinnedBy:"abc",
value:11
},
{
id:4,
pinnedBy:null,
value:12
},
];
My sorting conditions are
After applying sorting result will be
obj=[
{
id:3,
pinnedBy:"abc",
value:11
},
{
id:1,
pinnedBy:"abc",
value:9
},
{
id:4,
pinnedBy:null,
value:12
},
{
id:2,
pinnedBy:null,
value:10
}
];
How can I achieve this?
Upvotes: 4
Views: 75
Reputation: 386654
You could sort by the delta of a boolena value and then sort by value
property.
let array = [{ id: 1, pinnedBy: "abc", value: 9}, { id: 2, pinnedBy: null, value: 10 }, { id: 3, pinnedBy: "abc", value: 11 }, { id: 4, pinnedBy: null, value: 12 }];
array.sort((a, b) =>
(a.pinnedBy === null) - (b.pinnedBy === null) ||
b.value - a.value
);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 6