Sort array of objects in javascript with two sort conditions

Viewed 69

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

  1. pinnedBy items having value NOT null should be on top and it should be sorted in descending order by value.
  2. All other items should be below pinnedBy items and should be sorted in descending order by value.

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?

1 Answers

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

Related