4

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?

0

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.