按两个属性排序,其中一个属性优先但具有共同值?

时间:2017-02-22 17:25:22

标签: javascript arrays sorting

问题: 如何通过两个属性对data数组进行排序:

  1. 其中type始终位于顶部且
  2. 其中count始终从最小到最大。
  3. 这是我的努力:

    var data = [
      {type: 'first', count: '1'},
      {type: 'second', count: '5'},
      {type: 'first', count: '2'},
      {type: 'second', count: '2'},
      {type: 'second', count: '1'},
      {type: 'first', count: '0'},
    ]
    
    //Expected
    var newData = [
      {type: 'first', count: '0'},
      {type: 'first', count: '1'},
      {type: 'first', count: '2'},
      {type: 'second', count: '1'},
      {type: 'second', count: '2'},
      {type: 'second', count: '5'},
    ]
    
     //**Pseudo code**//
    // Will put the types on top
    data.sort((a,b) => a.type === 'first' ? -1:0)
    
    // This will sort the count 
    data.sort((a,b) => a.count < b.count ? -1 ? (a.count > b.count ? 1:0)
    

    由于count分享不同类型之间的值,我发现很难解决它。如何对这两个属性进行排序,但始终将类型保持在最顶层,并始终按从小到大的顺序计算?

1 个答案:

答案 0 :(得分:1)

您可以使用sort()这样的方法。

var data = [
  {type: 'first', count: '1'},
  {type: 'second', count: '5'},
  {type: 'first', count: '2'},
  {type: 'second', count: '2'},
  {type: 'second', count: '1'},
  {type: 'first', count: '0'},
]

var result = data.sort(function(a, b) {
  return ((b.type == 'first' ) - (a.type == 'first')) || (a.count - b.count)
})

console.log(result)