1

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
  • 15,447
  • 5
  • 79
  • 98
  • 1
    Possible duplicate of [Merge/flatten an array of arrays in JavaScript?](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript) – Hassan Imam Jan 20 '18 at 11:03

3 Answers3

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]
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

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]))
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

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]));
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Galoopi
  • 21
  • 1