首页 > 解决方案 > 如何在javascript中将数组中的重复项合并到该数组中的子数组中?

问题描述

我有:

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

我想要:

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

标签: javascript

解决方案


你可以这样做:

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)

推荐阅读