Smooth JavaScript array - why doesn't it work?

I am trying to smooth an array with randomly nested arrays inside. I'm not sure why the function I wrote ends in an infinite loop:

let array = [1, 2, [3]]
var final_array = [] 

function flattener(array){
  for(i = 0; i < array.length; i++){
    if(array[i] instanceof Array){
      flattener(array[i])
    }else{
      final_array.push(array[i])
    }
  }
}

flattener(array)

I think it MUST be:

When I am in the for loop for [3], it goes into the if statement, flattenergets called again, it resolves, and then I exit the if statement.

Instead, the if statement continues to trigger the check [3]indefinitely, and I'm not sure why this is happening.

+4
source share
4 answers

The problem is that you did not declare the variable i, so it leaked into the global space and was reset when it repeats.

Edit:

for(i = 0; i < array.length; i++){

To:

for(var i = 0; i < array.length; i++){
+8

, Array.reduce Array. CONCAT.

/**
 * Flattens an array of arrays into one-dimensional array
 * @param  {Array} arr: the array to be flattened
 * @return {Array}
 */
function flatten(arr) {
  return arr.reduce(function (flattened, cvalue) {
    return flattened.concat(Array.isArray(cvalue) ? flatten(cvalue) : cvalue);
  }, []); // initial value of flattened array []
}

...

let array = [1, 2, [3]]
var falttened = flatten(array)

: Array flatten

+2

Array#concatplus Array#mapis another way to achieve this.

var flattener = arr => [].concat.apply([], arr.map(item=>Array.isArray(item) ? flattener(item) : item));

or ES5 version

var flattener = function flattener(arr) {
  return [].concat.apply([], arr.map(function (item) {
    return Array.isArray(item) ? flattener(item) : item;
  }));
};
+2
source

Edit

 for(i = 0; i < array.length; i++)

to

 for(var i = 0; i < array.length; i++)
+1
source

Source: https://habr.com/ru/post/1672080/


All Articles