TechnoCorner TechnoCorner -4 years ago 115
Javascript Question

Flattening nested array (associated array) in JS

I'm trying to flatten an associated array but I'm getting undefined. I recently learnt

reduce
and am trying to apply the same logic.



var list2 = [0, [1, [2, [3, [4, [5]]]]]];

function flat3(arr){
arr.reduce(function(result, val, index){
if(Array.isArray(val)){
result = result.concat(val);
flat3(val);
} else {
result.push(val);
}
return result;
}, []);
}

console.log(flat3(list2));





I get undefined. Why? What am I missing?

Answer Source

You're not returning a value for flat3. This is what you're looking for:

var list2 = [0, [1, [2, [3, [4, [5]]]]]];

function flat3(arr) {
  return arr.reduce(function(result, val, index) {
    if (Array.isArray(val)) {
      result = result.concat(flat3(val));
    } else {
      result.push(val);
    }
    return result;
  }, []);
}

console.log(flat3(list2));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download