How do I turn a nested array into a flat one?

  • 0
    An array is given that can store any data type.
    you need to implement a function that expands nested arrays into the original array,
    other types of data must remain unchanged.
    Try to polyfill the flat method. Do not use the method itself in the solution.
    flatten([1, 'any [complex] string', null, function() {}, [1, 2, [3, '4'], 0], [], { a: 1 }]);
    // возвращает
    //      [1, 'any [complex] string', null, function() {}, 1, 2, 3, '4', 0, { a: 1 }]
    
    function flatten(list) {
        console.log(flatten)
    }
    JavaScript Jasper Hudson, Sep 14, 2019

  • 1 Answers
  • 0
    var list = [1, 'any [complex] string', null, function() {}, [1, 2, [3, '4'], 0], [], { a: 1 }];

    function flatten(arr) {
    var temp = [];
    for(var i = 0; i < arr.length; i++) {
    if(Array.isArray(arr[i])) {
    temp = temp.concat(flatten(arr[i]));
    } else {
    temp.push(arr[i]);
    }
    }
    return temp;
    }

    console.log(flatten(list));
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!