简体   繁体   中英

Sort array of objects in javascript with two sort conditions

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM