Search code examples
javascriptarraysdatabasedashboard

Transform nested arrays of integers into a flat array of integers - javascript


The work context of my question is data visualization. It is correct transforming nested arrays of integers into a flat array of integers in this way?

var inputArray = [[1, 2, [3]],4,[5, [6, [7,8],[9]]],10];

var inputArrayStr = inputArray.toString(); 
var outputArrayInt = JSON.parse("[" + inputArrayStr + "]");

console.log(outputArrayInt); // --> [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Solution

  • Actually:

    Take Array#flat with Infinity as parameter for a flat array of all levels:

    const
        input = [[1, 2, [3]], 4, [5, [6, [7, 8], [9]]], 10],
        output = input.flat(Infinity);
    
    console.log(output);


    Older Answer:

    I suggest to use a special function for this task.

    function flat(a) {
        var b = [];
        a.forEach(function (c) {
            if (Array.isArray(c)) {
                b = b.concat(flat(c));
            } else {
                b.push(c);
            }
        });
        return b;
    }
    
    var inputArray = [[1, 2, [3]], 4, [5, [6, [7, 8], [9]]], 10],
        outputArray = flat(inputArray);
    
    document.write('<pre>' + JSON.stringify(outputArray, 0, 4) + '</pre>');