The question is to use reduce () to work with an array of arrays and return a homogeneous array without sub-arrays. For example, [1,2, [3, [4,5]]] will return [1,2,3,4,5].
Here is the code that works, given that the sub-array itself is not another array of arrays -
var a = [3,[4,[5,[6,7]]]];
var b = 8;
var c = [9,10];
var x = []
var arr = [1,2,a,b,c];
arr = [1,2,3,4,c];
console.log(arr.reduce(function oneArray(a,b)
{
return a.concat(b);
},x))
Please note that I am changing my arr array since the code does not work for the first arr array ie [1,2, a, b, c]. For arr [1,2,3,4, c] the returned object is [1,2,3,4,9,10]
Here is my attempt to make it work for the first arr
function oneArray(a,b)
{
if (typeof b == "object")
b = b.reduce(oneArray(x,y),[]);
return a.concat(b);
}
console.log(arr.reduce(oneArray(a,b),x));
It gives me an error
Uncaught TypeError: [object Array] is not a function (anonymous function) @ Flattening.html: 27
It interprets my oneArray function as an array, not a function
, , ( ) , .
- , [1,2,3,4,5,6,78,9,10], (), -?