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

标签 javascript arrays sorting

问题: 如何按两个属性对 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)

由于 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/

相关文章:

javascript - 在 vs 2008 firefox 3.5+ 中调试

javascript - 在 Javascript 中对数组中递增的数字进行排序

c - 将文件中的数据存储到结构数组中

javascript - 从属性中获取所有值并插入数组

c - 如何在c中按字母顺序对链接列表进行排序

javascript - 在 React-Redux 中实时重新排序列表的最佳方法?

javascript - 如何从jquery ajax成功内部调用parents方法

javascript - 检测点击外部 react 父组件

javascript - 如何使用 jQuery 选择所有文本区域和文本框?

Javascript:将数组插入数组还是将值插入数组?