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]
Penny Liu
18k5 gold badges89 silver badges109 bronze badges
-
1Possible duplicate of Merge/flatten an array of arrays in JavaScript?Hassan Imam– Hassan Imam2018年01月20日 11:03:35 +00:00Commented Jan 20, 2018 at 11:03
3 Answers 3
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]
answered Jan 20, 2018 at 10:45
Ori Drori
196k32 gold badges243 silver badges233 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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]))
answered Jan 20, 2018 at 10:48
Nenad Vracar
122k16 gold badges160 silver badges184 bronze badges
Comments
lang-js