简体   繁体   English

JavaScript 展平嵌套数组

[英]JavaScript flatten nested array

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]

You are pushing to res the result of flatten , which is an array.您正在推动res的结果flatten ,这是一个数组。 Instead Array#concat the result of the inner flatten call to res , and assign the result to res .相反, Array#concat是对res的内部flatten调用的结果,并将结果分配给res

Note: to identify an array, you can use Array#isArray .注意:要识别数组,您可以使用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]

You can use concat instead of push and reduce instead of for loop.您可以使用concat代替pushreduce代替for循环。

 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]))

You can use the flat() method on the array as follows.您可以对数组使用flat()方法,如下所示。

 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]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM