问题:
如何按两个属性对 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 在不同类型之间共享值,我发现很难解决它。如何对这两个属性进行排序,但保持类型始终位于顶部,并始终按从小到大的顺序进行计数?
最佳答案
您可以像这样使用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)
关于javascript - 按两个属性排序,其中一个属性优先但具有共同值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42398326/