You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何扁平化嵌套数组并去除其中的重复元素

如何将嵌套数组扁平化并去除重复元素?

给定如下嵌套数组,需要将其转换为无重复元素的单一数组:

let input = [
  ['Apple', 'Banana'],
  ['Carrot', 'Peach'],
  ['Apple', 'Grapes'],
  ['Mango', 'Cherry'],
  ['Banana', 'Carrot'],
  ['Strawberry', 'Apple'],
  ['Peach', 'BlackBerry'],
  ['Orange', 'Apple'],
  ['Banana', 'Grapes']
]

// 注:你给出的expectedOutput存在笔误,"Apples"应为"Apple","Carrots"应为"Carrot",修正后的预期输出包含所有去重元素:
let expectedOutput = ["Apple", "Carrot", "Banana", "Grapes", 
                     "Orange", "Peach", "Cherry", "Strawberry", "BlackBerry", "Mango"];

你找到的方法完全可行,这是当前JavaScript中处理这类需求最简洁高效的方案之一,完整实现代码如下:

let input = [
  ['Apple', 'Banana'],
  ['Carrot', 'Peach'],
  ['Apple', 'Grapes'],
  ['Mango', 'Cherry'],
  ['Banana', 'Carrot'],
  ['Strawberry', 'Apple'],
  ['Peach', 'BlackBerry'],
  ['Orange', 'Apple'],
  ['Banana', 'Grapes']
];

// 1. 扁平化嵌套数组
const flattenedArr = input.flat();
// 2. 通过Set去重,再转回数组
const uniqueArray = [...new Set(flattenedArr)];

console.log(uniqueArray);
// 输出:["Apple", "Banana", "Carrot", "Peach", "Grapes", "Mango", "Cherry", "Strawberry", "BlackBerry", "Orange"]

步骤解释:

  • input.flat():ES2019引入的数组方法,默认会扁平化一层嵌套的数组;如果有更深层级的嵌套,可以传入参数flat(Infinity)处理任意深度的嵌套结构。
  • new Set(flattenedArr):Set是ES6引入的集合类型,天然具备自动去重的特性,将扁平化后的数组传入Set即可得到无重复元素的集合。
  • [...new Set(flattenedArr)]:使用扩展运算符...将Set集合转换回数组类型,最终得到无重复的一维数组。

兼容旧环境的替代方案:

如果需要兼容不支持flat()和扩展运算符的旧环境,可以用reduce完成扁平化,再结合filter去重:

// 扁平化数组
const flattenedArr = input.reduce((acc, curr) => acc.concat(curr), []);
// 去重
const uniqueArray = flattenedArr.filter((item, index, arr) => arr.indexOf(item) === index);

内容的提问来源于stack exchange,提问作者Amey079

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:15:51