Home > Software design >  what does it mean to mention the original array after an else operator?
what does it mean to mention the original array after an else operator?

Time:04-21

I am studying by looking at different answers for question in freecodecamp and I came across this one that I can't figure out the last part:

function steamrollArray(arr) {
    const flat = [].concat(...arr);
    return flat.some(Array.isArray) ? steamrollArray(flat) : flat;
  }
  
  console.log(steamrollArray([[3, [[4]]]]));

Why does it say "flat" after the "else :", like what does that mean? It just mention the original array, there is nothing going on like .push() or other methods.

CodePudding user response:

The line with the return basically does:

  1. If at least one item inside the flat array is another Array, it will process steamrollArray (so this is a recursive function)
  2. If the some method returns false, it will return the flat variable as it is. The flat variable will be eventually a number, meaning .some will return false and exit one level of the recursiveness and so on.

Running the code makes it easier to understand, as well as the documentation on the .some() JS function.

function steamrollArray(arr) {
    const flat = [].concat(...arr);
    return flat.some(Array.isArray) ? steamrollArray(flat) : flat;
  }
  
 console.log(steamrollArray([[3, [[4]]]]));
 //output = [3,4]

CodePudding user response:

it is referring to the original flat variable in this line:

const flat = [].concat(...arr);

which will be returned if this line is false:

flat.some(Array.isArray)

CodePudding user response:

The key is the return preceding the expression: flat is not being modified because it is flat and is ready to be returned as the final value of the function.

I think the function can be reworded more clearly like this:

function steamrollArray(arr) {
    const flat = [].concat(...arr);
    if (flat.some(Array.isArray)) { // check if the array is not flat
        return steamrollArray(flat); // if it is not flat, process it more
    }
    return flat; // return a completely flat array
}
  
console.log(steamrollArray([[3, [[4]]]]));
  • Related