JavaScript flatten nested array

一个人想着一个人 提交于 2021-02-17 03:41:10

问题


I am trying to flatten any length of a nested array into a single array. Why it's showing array rather than array value?

function flatten(arr) {
  var res = [];
  for (var i = 0; i < arr.length; i++) {
    if (toString.call(arr[i]) === "[object Array]") {
      res.push(flatten(arr[i]));
    } else {
      res.push(arr[i]);
    }
  }
  return res;
}

console.log(flatten([1, 2, [3, [4, 5, [6]]], 7, 8]));
// [1, 2, Array(2), 7, 8]

回答1:


You are pushing to res the result of flatten, which is an array. Instead Array#concat the result of the inner flatten call to res, and assign the result to res.

Note: to identify an array, you can use Array#isArray.

function flatten(arr) {
  var res = [];
  for (var i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      res = res.concat(flatten(arr[i]));
    } else {
      res.push(arr[i]);
    }
  }
  return res;
}
console.log(flatten([1, 2, [3, [4, 5, [6]]], 7, 8])); // [1, 2, Array(2), 7, 8]



回答2:


You can use concat instead of push and reduce instead of for loop.

const flatten = data => data.reduce((r, e) => {
  return r = r.concat(Array.isArray(e) ? flatten(e) : e), r
}, [])
 
console.log(flatten([1, 2, [3, [4, 5, [6]]], 7, 8]))



回答3:


You can use the flat() method on the array as follows.

function flatten(arr) {
  return arr.flat(10) //the number in brackets are the depth level 
}

console.log(flatten([1, 2, [3, [4, 5, [6]]], 7, 8]));


来源:https://stackoverflow.com/questions/48355103/javascript-flatten-nested-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!