数组扁平化是将多维数组转化为一维数组的过程,1. 可通过递归遍历并拼接元素实现;2. 使用reduce方法结合递归累积结果;3. 利用...扩展运算符与some方法循环展开数组;4. 调用es2019新增的flat()方法并传入深度参数(如infinity完全扁平化);5. 处理空值时默认保留null和undefined,需额外使用filter方法移除;6. flat()方法性能最优,尤其适合已知深度的场景;7. 所有方法均支持字符串、对象等非数字类型,但对象仍为引用类型;8. 可通过flat(depth)控制扁平化层级,实现部分降维,适用于结构化数据处理,最终应根据兼容性与性能需求选择合适方案。

数组扁平化,简单来说,就是把一个多维数组降维,变成一个一维数组。实现方式有很多,关键在于如何处理嵌套的数组。

解决方案
实现数组扁平化,可以使用递归、
reduce
...
flat()

function flatten(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i])); // 递归调用
} else {
result.push(arr[i]);
}
}
return result;
}
const nestedArray = [1, [2, [3, 4], 5], 6];
const flatArray = flatten(nestedArray);
console.log(flatArray); // 输出: [1, 2, 3, 4, 5, 6]reduce
reduce
function flattenWithReduce(arr) {
return arr.reduce((acc, val) => {
return Array.isArray(val) ? acc.concat(flattenWithReduce(val)) : acc.concat(val);
}, []);
}
const nestedArray = [1, [2, [3, 4], 5], 6];
const flatArray = flattenWithReduce(nestedArray);
console.log(flatArray); // 输出: [1, 2, 3, 4, 5, 6]...
some
function flattenWithSpread(arr) {
while (arr.some(Array.isArray)) {
arr = [].concat(...arr);
}
return arr;
}
const nestedArray = [1, [2, [3, 4], 5], 6];
const flatArray = flattenWithSpread(nestedArray);
console.log(flatArray); // 输出: [1, 2, 3, 4, 5, 6]flat()
Infinity
const nestedArray = [1, [2, [3, 4], 5], 6]; const flatArray = nestedArray.flat(Infinity); console.log(flatArray); // 输出: [1, 2, 3, 4, 5, 6]
空值,比如
null
undefined
const nestedArrayWithNull = [1, [2, null, [3, 4], undefined, 5], 6]; const flatArrayWithNull = nestedArrayWithNull.flat(Infinity); console.log(flatArrayWithNull); // 输出: [1, 2, null, 3, 4, undefined, 5, 6] // 移除空值 const flatArrayWithoutNull = flatArrayWithNull.filter(val => val !== null && val !== undefined); console.log(flatArrayWithoutNull); // 输出: [1, 2, 3, 4, 5, 6]
flat()
reduce
...
flat()

在实际应用中,如果数组嵌套深度已知,使用指定深度的
flat()
...
数组扁平化不仅仅适用于数字数组,也可以处理包含字符串、对象等其他类型的数组。上述方法都能正确处理这些情况,不会因为类型不匹配而报错。
const mixedArray = [1, "hello", [2, { name: "world" }, 3], 4];
const flatMixedArray = mixedArray.flat(Infinity);
console.log(flatMixedArray); // 输出: [1, "hello", 2, { name: "world" }, 3, 4]需要注意的是,如果数组中包含对象,扁平化后对象仍然是引用类型,修改扁平化后的对象会影响原始数组中的对象。
有时候我们并不需要完全扁平化数组,而是只需要扁平化到特定的深度。
flat()
const nestedArray = [1, [2, [3, [4, 5]]]]; const flatArrayDepth1 = nestedArray.flat(1); console.log(flatArrayDepth1); // 输出: [1, 2, [3, [4, 5]]] const flatArrayDepth2 = nestedArray.flat(2); console.log(flatArrayDepth2); // 输出: [1, 2, 3, [4, 5]]
这个特性在处理层级结构的数据时非常有用,可以根据实际需求控制扁平化的程度。
以上就是js如何实现数组扁平化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号