javascript - 如何在javascript中将数组中的重复项合并到该数组中的子数组中?
问题描述
我有:
['a', 'b', 'd', 'a', 'f', 'b', 'a', 'b']
我想要:
[['a', 'a', 'a'], ['b', 'b', 'b'], ['d'], ['f']]
解决方案
你可以这样做:
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)
推荐阅读
- c# - 将 .net core 2.2 迁移到 3.1 问题
- delphi - 特定代码行上的 Delphi 访问冲突错误
- python - 如何防止odoo创建重复字段?
- winapi - 如何识别从 msvc 中的线程或进程调用的函数
- python - 使用 Python 从 XSD 构建 XML 文件
- java - 计时器需要很长时间才能启动
- r - 在循环期间使用 rbind 添加 0 值
- node.js - 如何在当前 HTML 页面上使用 express 从 res.json 呈现 json 对象
- python - 如何更新用户输入之间的情节?
- firebase - 如何保护用作 Diaglogflow / Google Action 主机的 Google 云功能