Angel Politis Angel Politis - 3 months ago 13
Javascript Question

How to get all values out of array and its sub-arrays

I'm trying to build a function that will be applied to an array and will extract all its values which are not arrays.

For the ones that are arrays, it will do the same process again until all the values from the first array, its sub-arrays, the sub-arrays' own sub-arrays and so on will be put into a single array.

The problem I'm facing lies upon the fact that I won't know beforehand how many sub-arrays each array will have and so on.

What I've tried:

I have tried using

forEach()
as shown below, but as I said above the number of sub-arrays and the values in general is unknown beforehand. I'm sure that some kind of looping or maybe even recursion would help, but I can't get it to work in my mind.

function extract (value) {
var
result = [],
isArray = function (value) {
return value.constructor === Array;
}

if (isArray(value)) {
value.forEach(function (each) {
if (!isArray(each)) result.push(each);
else {
each.forEach(function (j) {
if (!isArray(each)) result.push(each);
else... // same as above
});
}
});
}

return result;
}


I believe that using
each = each[i]
as if I were looking for descendant in the DOM would help, but I'm not sure how to set up the
while
loop in this case and what the terminating condition should be.

Desired Result:

var array = [["a", 2, [3, "mn"], "bu"], "la", [12, 34, "ab"]]; // Just an example
var result = extract(array); // Outputs: ["a", 2, 3, "mn", "bu", "la", 12, 34, "ab"]


How can I fix my current code in order to achieve the desired result above?

Answer

A solution with recursion:

function extract( array, newarray ){
    if( !newarray ) newarray = [] ;
    if( array ) for( var i = 0 ; i < array.length ; ++i )
    {
        if( array[i].constructor.name === "Array" ) extract( array[i], newarray ) ;
        else newarray.push( array[i] ) ;
    }
    return newarray ;
}
var array = [["a", 2, [3, "mn"], "bu"], "la", [12, 34, "ab"]]; // Just an   
var newarray = extract(array); // Outputs: ["a", 2, 3, "mn", "bu", "la", 12, 34, "ab"]
console.log( newarray ) ;

Comments