lodash sortBy then groupBy, is order maintained?

前端 未结 3 902
Happy的楠姐
Happy的楠姐 2021-02-14 10:56

I\'m having trouble figuring out from the lodash documentation if my assumption about sorting and grouping is correct.

If I use sortBy, then use groupBy, do the arrays p

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 11:23

    It's not. Here's example, where order is not retained:

    const data = [
      {
        item: 'item1',
        group: 'g2'
      },   {
        item: 'item2',
        group: 'g3'
      },   {
        item: 'item3',
        group: 'g1'
      },   {
        item: 'item4',
        group: 'g2'
      },   {
        item: 'item5',
        group: 'g3'
      }
    ]
    
    const groupedItems = _(data).groupBy(item => item.group).value()
    

    In this case one would expect that group order would be: g2, g3, g1 - reality is that they are sorted g1, g2, g3.

    You can re-sort them with original array though.

    const groupedItems = _(data)
      .groupBy(item => item.group)
      .sortBy(group => data.indexOf(group[0]))
      .value()
    

    This will ensure original order of items.

提交回复
热议问题