3

I have an array of Objects. In some Objects key { liked:true } is present. I wish to sort them as all Objects having liked value on top of the array and remaining after them. There are some objects having key { liked:true }. I wish to sort whole array Objects as those Objects having key {liked : true} comes at the top of array and those which didn't have key {liked :true} will come afterwards.

var arr = [ { e:1, f: 2}, {liked:true, a:1, b: 2},{ g:1, h: 2},{liked:true, c:1, d: 2}]

I have tried this but It didn't work.

 arr.sort(function(a, b){
      return b.liked
    })

I expect that all Objects having key {liked:true} comes on top in array.

Deeksha gupta
  • 511
  • 2
  • 13

2 Answers2

5

If compareFunction is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction). If a and b are two elements being compared, then:

  1. If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).
  2. If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  3. If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).
  4. compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned, then the sort order is undefined.
 arr.sort(function(a, b){
      return b.liked? 1 :-1;
    })
Asnim P Ansari
  • 1,003
  • 9
  • 21
  • 1
    If you want to keep the original order as a sub-order (and not rely on the value of the key being "truthy"): `[{ a: 1 }, { liked: 1 }, { liked: 2 }, { a: 2 }, { liked: 3 }].sort((item1, item2) => (!('liked' in item1) && 'liked' in item2 ? 1 : -1)); ` – Shl Sep 10 '20 at 09:39
0

Your example already works in node v10.16.0

var arr = [ { e:1, f: 2}, {liked:true, a:1, b: 2},{ g:1, h: 2},{liked:true, c:1, d: 2}]

arr.sort(function(a, b){
  return b.liked
})

console.dir(arr)

This results in the output:

[ { liked: true, c: 1, d: 2 },
  { liked: true, a: 1, b: 2 },
  { e: 1, f: 2 },
  { g: 1, h: 2 } ]

See CodeSandbox: https://codesandbox.io/s/confident-platform-bq7u0

Edit: having said that, it's probably better to ensure your compare function gives the proper range of outputs (-1, 0, 1).