Create an Array concatAll method

Jafar Husain
InstructorJafar Husain
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 5 years ago

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.

[00:00] Thus far we've learned about three of the arrays methods, for each, map, and filter. In the previous example we learned that we could chain map and filter together to transform arrays into new arrays. Then we can use the for each method to consume all the data in the newly created transformed away and then do something with it, like print it out to the console.

[00:22] Working with arrays is common, but even more common in programming is working with nested data structures like arrays of arrays, for example. Let's take a look at how we can use functions to flatten these nested data structures so that we can then further transform them.

[00:36] An example of a nested data structure is the entire stock market. The entire stock market is actually made up of several exchanges. Each of these exchanges has multiple stocks. I've represented this here as a nested data structure, an array of arrays.

[00:52] The first array is stock records for the Dow Industrial today. The next array is stock records for the NASDAQ. Let's imagine that we want to print out all of the stocks in all of the exchanges. One thing we can do is nest for each.

[01:10] I'm going to call the for each method on exchanges, pass in a function that accepts the exchange. Then I'm going to for each over all of the stocks in each exchange. Finally I'm going to print each stock to the screen.

[01:38] If everything went well we should see all of the stock records printed out to the console. Sure enough we see all the stocks from all of the exchanges. It turns out that we can take this very common pattern and we can abstract it into a useful function.

[01:57] This function is called concat all. Unlike map, filter, and for each, it doesn't already exist on the array, so we're going to add it. The concat all function is very, very simple. It doesn't even accept any arguments. You run it on a nested array, and it creates a new array that contains the flattened resulted of that nested array.

[02:20] Let's take a look at how we would execute this. We're going to follow the exact same pattern that we had in the example below. We're going to take this, which in this context is the outer array, and we're going to run for each on it. Each one of those items is expected to be another array, a subarray if you will.

[02:39] Then we're going to call for each on the subarray. For every item in there we're going to add that item to a new collection of results. Finally concat all returns the results. Notice that concat all only flattens a nested array by one dimension.

[03:05] If we were to run concat all on a three dimensional array, it would output a two dimensional array. On a four dimensional array a three dimensional array, a two dimensional array a one dimensional array, and so on.

[03:16] Notice also that concat all will not work on a flat array because it assumes that each item in the array is another array. Concat all can only be used on arrays of two or more dimensions. Now I can take the code below and replace it with concat all, call for each, get all the stocks, and format this slightly differently.

[03:53] I've created a new array containing only the stocks in all the exchanges. Now I'm going to for each over it, and I'm going to log the stock to the console. I'll comment out this code here, and we should see that when we run this we get the identical result.

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.


~ 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 {
    return outputArray;
  return flattenArray(this, []);

Markdown supported.
Become a member to join the discussionEnroll Today