1

I need to flatten multidimensional arrays but my code only flattens one array and then stops. What is wrong? How do I get it to only transfer the elements with no arrays.

 function flatten(arr) {
     // I'm a steamroller, baby
     arr.reduce(function (flat, toFlatten) {
        return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
     },[]);
    }
    flatten([[['a']], [['b']]]); 

assert.deepEqual(flatten([[['a']], [['b']]]), ['a', 'b'], 'should flatten nested arrays');

should flatten nested arrays: expected [ [ 'a' ], [ 'b' ] ] to deeply equal [ 'a', 'b' ]
1

2 Answers 2

1

You're doing it right -- just missing a return statement.

function flatten(arr) {
    // I'm a steamroller, baby
    return arr.reduce(function (flat, toFlatten) {
        return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
    }, []);
}

console.log(flatten([[['a']], [['b']]])); 
Sign up to request clarification or add additional context in comments.

Comments

0
let myarray = [
    1000,
    [1, 2, 3, 4],
    [5, 6, 7],
    [999, [10, 20, [100, 200, 300, 400], 40], [50, 60, 70]],
  ];
  
function f(array) {
  let result = [];
  function flatten(array) {
    for (let i = 0; i < array.length; i++) {
      if (!Array.isArray(array[i])) {
        result.push(array[i]);
      } else {
        flatten(array[i]);
      }
    }
    return result;
  }
  return flatten(array);
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.