zlx362211854 / daily-study

每日一个知识点总结,以issue的形式体现
10 stars 6 forks source link

111.实现一个 flattenDeep 函数,把嵌套的数组扁平化 #167

Open roxy0724 opened 4 years ago

goldEli commented 4 years ago
var arr = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];

function deepFlatten(arr) {
  return arr.reduce(
    (res, item) =>
      Array.isArray(item) ? [...deepFlatten(item), ...res] : [item, ...res],
    []
  );
}

console.log(deepFlatten(arr)); // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
zlx362211854 commented 4 years ago
var a = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]

function merge(arr) {
  return arr.reduce((a, b) => {
    if (Array.isArray(b)) {
      return [...merge(b), ...a]
    } else {
      return [b, ...a]
    }
  }, [])
}
merge(a)

same as #130