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]

1

3 Answers 3

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]

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.