代码之家  ›  专栏  ›  技术社区  ›  Toucouleur

_.groupBy,但首先排序

  •  0
  • Toucouleur  · 技术社区  · 6 年前

    我有这个阵列,

    我需要组队 id ,但首先按 timestamp

    sample_array = [
        {id: 21, timestamp:1, year: 2012},
        {id: 11, timestamp:2, year: 2017},
        {id: 12, timestamp:3, year: 2016},
        {id: 11, timestamp:4, year: 2014},
        {id: 11, timestamp:5, year: 2015},
        {id: 19, timestamp:6, year: 2016},
        {id: 12, timestamp:7, year: 2016}
        ]
    

    我想通过使用 underscore.js 首先使用时间戳对数组进行排序,然后检查是否存在同一ID的另一个条目,然后在下一个ID之前对其进行分组:

    预期结果:

    [
        {id: 21, timestamp:1, year: 2012},
        {id: 11, timestamp:2, year: 2017},
        {id: 11, timestamp:4, year: 2014},
        {id: 11, timestamp:5, year: 2015},
        {id: 12, timestamp:3, year: 2016},
        {id: 12, timestamp:7, year: 2016},
        {id: 19, timestamp:6, year: 2016}
    ]
    

    我试图通过使用 _.groupBy _.sortBy .

    需要:

    1. 按id分组
    2. 按组中的时间戳排序
    3. 按组的最小时间戳(每个组中的第一个时间戳)对组进行排序
    3 回复  |  直到 6 年前
        1
  •  1
  •   skyboyer    6 年前

    基于下一步的理解:

    按id分组,按每个组中的时间戳排序,然后按组的最小时间戳(实际上是每个组中的第一个时间戳)对组进行排序,并将组展平到平面列表中。

    _.chain(sample_array)
     .groupBy('id')
     .mapObject(groupPerId=> _.sortBy(groupPerId, 'timestamp'))
     .sortBy(groupPerId=> groupPerId[0].timestamp)
     .flatten()
     .value()
    
        2
  •  2
  •   Nina Scholz    6 年前

    你可以根据 timestamp 然后按 id ,但不要使用数字,因为数字在对象中排序到顶部。因此,需要将数字转换为字符串并按其分组。

    然后映射值并展平数组。

    var array = [{ id: 21, timestamp:1, year: 2012 }, { id: 11, timestamp:2, year: 2017 }, { id: 12, timestamp:3, year: 2016 }, { id: 11, timestamp:4, year: 2014 }, { id: 11, timestamp:5, year: 2015 }, { id: 13, timestamp:6, year: 2016 }, { id: 12, timestamp:7, year: 2016 }],
        result = _.chain(array)
            .sortBy(['timestamp'])
            .groupBy(o => _ + o.id)
            .map(v => v)
            .flatten()
            .value();
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
        3
  •  0
  •   Naim Sulejmani    6 年前

    如果这个数组是问题,你可以简单地解决如下,如果零加上时间戳,你可以玩数字,每一个时间戳取确切的数字:),检查它应该工作(这个例子最多是5个数字的时间戳),如果它有更多的话你可以在开始时添加零点。

        sample_array.sort(function(a,b){
    return Number(a.id.toString()+('00000'+a.timestamp.toString()).substr(a.timestamp.toString().length-1))-Number(b.id.toString()+('00000'+b.timestamp.toString()).substr(b.timestamp.toString().length-1))
    })