Sort according to key exists in array Object [duplicate]

问题: This question already has an answer here: Sort JavaScript object by key 26 answers I have an array of Objects. In some Objects key { liked:true } i...

问题:

This question already has an answer here:

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.


回答1:

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

回答2:

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).

  • 发表于 2019-07-05 10:51
  • 阅读 ( 110 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除