【问题标题】:how do you group adjacent same type items in list using Lodash?你如何使用 Lodash 对列表中相邻的相同类型的项目进行分组?
【发布时间】:2022-10-02 03:46:14
【问题描述】:

例如,我有一个 [A,A,A,B,B,B,A,A,C,C] 列表,我想将其转换为:

[
  [A,A,A],
  [B,B,B],
  [A,A], // repeated type. but since this \"group\" is not adjacent to the first one, so it is in its own group
  [C,C],
]

这对 lodash 可行吗?

    标签: javascript lodash


    【解决方案1】:

    将数组缩减为带有子数组的新数组。如果没有子数组,或者当前项等于最后一个子数组的最后一项,则使用当前项添加一个新的子数组。如果不是,则将当前项推送到最后一个子数组:

    const arr = ['A','A','A','B','B','B','A','A','C','C']
    
    const result = arr.reduce((acc, v) => {
      const last = acc.at(-1)
      
      if(v !== last?.at(-1)) acc.push([v])
      else last.push(v)
      
      return acc
    }, [])
    
    console.log(result)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 2015-02-23
      • 2022-12-18
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2020-08-14
      • 2016-08-25
      相关资源
      最近更新 更多