Skip to content

JavaScript 数组拍平方法

Published: at 12:58 PMSuggest Changes

问题

手写一个拍平数组的方法,拍成一维数组

[1, [1, 2, 3, [6, 7, 8, [10, 11, 12, 13]]], 4, 5] -> [1, 1, 2, 3, 6, 7, 8, 10, 11, 12, 13, 4, 5]

题解

function flatArray(array) {
  return array.reduce((acc, data) => {
    return Array.isArray(data) ? acc.concat(flatArray(data)) : [...acc, data];
  }, []);
}

console.log(flatArray([1, [1, 2, 3, [6, 7, 8, [10, 11, 12, 13]]], 4, 5]));


Previous Post
Babel 和 Webpack 兼容 IE8 的实践
Next Post
JavaScript 随机排序数组