【问题标题】:How can I combine duplicates in array into subarrays in this array in javascript? [duplicate]如何在javascript中将数组中的重复项合并到该数组中的子数组中? [复制]
【发布时间】:2021-09-30 17:28:54
【问题描述】:

我有:

['a', 'b', 'd', 'a', 'f', 'b', 'a', 'b']

我想要:

[['a', 'a', 'a'], ['b', 'b', 'b'], ['d'], ['f']]

【问题讨论】:

标签: javascript


【解决方案1】:

你可以这样做:

const test = ["a", "b", "d", "a", "f", "b", "a", "b"]

function parseElements(elements) {
  const temp = {}
  for (const element of test) {
    if (!temp[element]) {
      temp[element] = []
    }
    temp[element].push(element)
  }

  return [...Object.values(temp)]
}

const result = parseElements(test)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2017-07-03
    相关资源
    最近更新 更多