1
问: 如何通过两个属性排序我data
阵列:按两个属性排序,其中一个优先但具有共同的值?
- 其中
type
总是在顶部和 - 其中计数总是从最小到最大。
这是我的努力:
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)
由于计数器份额不同类型之间的值,我发现很难解决这个问题。我怎样才能对这些属性进行排序,但始终将类型保持在最高,并且始终按照从小到大的顺序进行计数?
为什么没有'类型: '第二',数:“在你的'newData' 1''元素?你是否期望你的“排序”算法省略它,因为最后一个'first'元素的count大于它自己? –
对不起良好的抓 –
多少种可能呢?您可能必须为此编写自定义排序 –