cachaito
6/3/2016 - 7:59 AM

Flattening arrays #2

// 1. The classical recursive way
function baseFlatten(array, depth, predicate, isStrict, result) {
  // lots of code here
  if (depth > 1) {
    // Recursively flatten arrays (susceptible to call stack limits).
    baseFlatten(value, depth - 1, predicate, isStrict, result);
  } else {
    arrayPush(result, value);
  }
}

// 2. 
function flatten(arr) {
  if(!Array.isArray(arr)) {
    return [arr];
  }

  var array = [];
  for(var i = 0; i < arr.length; i++) {
    array = array.concat(flatten(arr[i]));
  }
  return array;
}

flatten([1,[2,[3]],[4]]); // => [1,2,3,4]


// 3. The iterative way
function flatten(arr) {
  var array = [];
  while(arr.length) {
    var value = arr.shift();
    if(Array.isArray(value)) {
      // this line preserve the order
      arr = value.concat(arr);
    } else {
      array.push(value);
    }
  }
  return array;
}

flatten([1,[2,[3]],[4]]); // => [1,2,3,4]