问题:
如何通过两个属性对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)
由于count分享不同类型之间的值,我发现很难解决它。如何对这两个属性进行排序,但始终将类型保持在最顶层,并始终按从小到大的顺序计算?
答案 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)