1

I'm trying to flatten a nested 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?

TechnoCorner
  • 4,151
  • 8
  • 27
  • 62
  • why don't you just use this... https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce – A. L Mar 01 '17 at 03:34
  • 1
    You're getting `undefined` because you're not returning `arr.reduce` for `flat3` – JohanP Mar 01 '17 at 03:37
  • @A.Lau I don't want to use ES6's => instead i want to understand it in ES5 first. Can you please help me solve the problem? – TechnoCorner Mar 01 '17 at 03:40
  • I don't see why my post has got a -1 for asking a question (And even presenting my basic attempt) – TechnoCorner Mar 01 '17 at 03:41
  • 1
    Unfortunately, some people will dislike it even if they remotely think it's not worth answering – A. L Mar 01 '17 at 03:50
  • What is an associated array? –  Mar 01 '17 at 03:54
  • @torazaburo people can correct me if i'm wrong. Javascript does not inherently have associated array but it's prety much array inside array (deep nested array) – TechnoCorner Mar 01 '17 at 03:55
  • Then call it a deeply nested array. –  Mar 01 '17 at 03:55
  • I'll change the title. the reason why i called it associated array because it's a common terminology coming from other programming languages. – TechnoCorner Mar 01 '17 at 03:56
  • The term you were looking for was probably "associative array", but that means something different--it refers to an "array" whose elements are indexed by strings, usually, which is what in JS is called an "object". –  Mar 01 '17 at 03:58

1 Answers1

2

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));
4castle
  • 28,713
  • 8
  • 60
  • 94
JohanP
  • 4,244
  • 1
  • 18
  • 30