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' ]
Rob Lyndon
  • 12,089
  • 5
  • 49
  • 74
Eric Park
  • 502
  • 2
  • 7
  • 23
  • possible duplicate of [Merge/flatten an Array of Arrays in JavaScript?](http://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript) – Nick Grealy Jul 01 '15 at 23:08

2 Answers2

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']]])); 
Rob Lyndon
  • 12,089
  • 5
  • 49
  • 74
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);
}
YousefHany
  • 11
  • 1
  • 1
  • 1
    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](/help/how-to-answer). – Community Mar 02 '22 at 01:04