2017-02-22 66 views
1

问: 如何通过两个属性排序我data阵列:按两个属性排序,其中一个优先但具有共同的值?

  1. 其中type总是在顶部和
  2. 其中计数总是从最小到最大。

这是我的努力:

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) 

由于计数器份额不同类型之间的值,我发现很难解决这个问题。我怎样才能对这些属性进行排序,但始终将类型保持在最高,并且始终按照从小到大的顺序进行计数?

+0

为什么没有'类型: '第二',数:“在你的'newData' 1''元素?你是否期望你的“排序”算法省略它,因为最后一个'first'元素的count大于它自己? –

+0

对不起良好的抓 –

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

相关问题