Overwriting the smoothing function

I wrote a version of the _.flatten underscore function, and it works, but I donโ€™t understand why the first one works, but not the second version.

var flatten = function (array, result) {
  var result = [];
  for (var i = 0; i < array.length; i++) {
    var current = array[i];
    if (Array.isArray(current)) {
      result.push.apply(array, flatten(current));
    }
    else {
      result.push(current);
    }
  }
  return result;
};

var nested = [1, [2], [3, [[[4]]]]];
console.log(flatten(nested));
// [1,2,3,4]

vs

var flatten = function (array, result) {
  var result = [];
  array.forEach(function (current) {
    if (Array.isArray(current)) {
      result.push.apply(array, flatten(current));
    }
    else {
      result.push(current);
    }
  });
  return result;
};
var nested = [1, [2], [3, [[[4]]]]];
console.log(flatten(nested));
// [1]
+4
source share
1 answer

You pass the wrong first argument result.push.apply:

result.push.apply(array, flatten(current));
// ---------------^^^^^

You want to call pushon result, but actually you call array.push. You want to say:

result.push.apply(result, flatten(current));

so it pushgets resultits own thiswhen it is called.


A more interesting question is why your based implementation is forโ€œworking,โ€ even if its implementation is confused. If you throw it away

console.log(nested);

, , for ; , "".

if:

if (Array.isArray(current)) {
  result.push.apply(array, flatten(current));
}
else {
  result.push(current);
}

, array, . , array, , - result, .

:

var nested = [1, [2], [3, [[[4]]]], 5]

, -, :

[1, 5, 2, 3, 4]

( nested). , for, , .

+5

All Articles