Create an Array concatAll method

Share this video with your friends

Send Tweet

In addition to flat Arrays, programmers must often deal with nested Arrays. For example let's say we have an Array of stock exchanges, each of which is represented by an array of all the stocks listed on that exchange. If we were looking for a stock that matched a certain criteria, we would first need to loop through all of the exchanges, and then all of the stocks within.

In these situations, most developers would nest two loops. However in this lesson we will write a new Array function concatAll which will automatically flatten nested arrays buy one dimension. This will remove the need to ever use a nested loop to flatten a nested array.

Kevin Woodfield
Kevin Woodfield
~ 9 years ago

I've been in discussions and code reviews where some "senior" developers would frown upon nested foreach loops.

Could you give any insight into why this would be a bad thing? Maybe I misunderstood and he meant the for loop, not forEach(). Either way, it would be interesting to hear your opinion.

Cheers.

Andreas
Andreas
~ 7 years ago

Array.prototype has also a method named concat, which concatenates arrays. So the following is a smaller implementation of concatAll:

Array.prototype.concatAll = function() {
    return [].concat(...this);
};

In this case, ... is an array deconstruction. The result of ...this is all array elements provided to concat as parameters. [].concat(...this) concatenates all of the array elements of the containing array (this) with the empty array at the beginning.

Olga  Streltsova
Olga Streltsova
~ 7 years ago

Why not write something like below, which doesn't assume a certain number nestings.

  [
      { symbol: "XFX", price: 240.22, volume: 23432 },
      { symbol: "TNZ", price: 332.19, volume: 234 }
    ],
  [
      { symbol: "JXJ", price: 120.22, volume: 5323 },
      { symbol: "NYN", price: 88.47, volume: 98275 }
    ]
];

Array.prototype.concatAll = function() {
  function flattenArray(nestedArray, outputArray) {
    if (Array.isArray(nestedArray)) {
      
      nestedArray.forEach(function(nestedArrayItem) {
        flattenArray(nestedArrayItem, outputArray);
      });
      
    } else {
      outputArray.push(nestedArray);
    }
    return outputArray;
  }
  return flattenArray(this, []);
}


console.log(exchanges.concatAll());```