按金额分组并显示第一个和最后一个位置

Group by amount and display first and last position

本文关键字:第一个 最后一个 位置 显示 金额      更新时间:2023-09-26

你好,我有这些数据:

[
 {amount:1, position:1},
 {amount:1, position:2}, 
 {amount:1, position:3}, 
 {amount:2, position:4}, 
 {amount:2, position:5}
]

我想把它们转换成

[{amount: 1, range: "1-3"}, {amount: 2, range: "4-5"}]

有图书馆能做到这一点吗?

编辑

我第一次尝试使用下划线。我按数量对它们进行分组,然后绘制它们的地图。但这是最好的方式吗?

data = _.groupBy(data, function (item) {
    return item.amount;
})
data = _.map(data, function (item, index) {
    return {
        amount: index,
        range: _.first(item).position + "-" + _.last(item).position
    }
})

我可以建议您使用http://underscorejs.org或https://lodash.com,它们都没有直接解决你问题的功能,但你可以创造性地将一些现有功能结合起来:)祝你好运。

您应该学习函数式编程=]<3

var y = [{amount:1, position:1},{amount:1, position:2}, {amount:1, position:3}, {amount:2, position:4}, {amount:2, position:5}]
var amounts = []
y.map(function(obj){
  obj = y.reduce(function(a,i,ii){
    if (ii === 1){
      if (a.amount === obj.amount){
        a.position = 1
        a.set = true
      }else{
        a.amount = obj.amount
        a.set = false
      }
      return a
    }
    if (i.amount === a.amount && !a.set){
      a.set = true
      a.position = i.position
      return a
    }
    if (a.amount === i.amount)
      a.range = i.position
  
    return a
  })
  return {amount:obj.amount,range:obj.position+'-'+obj.range}
})
.filter(function(obj){
  if (!amounts[obj.amount]){
    amounts[obj.amount] = true
    return true
  }
  return false
})

相关文章: