Flattening a 2D array to use map/reduce I have been trying to get better at functional programming, which includes understanding map/reduce. I wrote a function intended to fill an autocomplete with values. The challenge I was encountering was my Mongo records, which had a category array that needed to be flattened for the autocomplete to work. Being a novice, I somehow came up with this code, and it works. But I know there must be a better way to do it using map/reduce.

You will see cats stores a call that uses .map, but it's the code from the package example and I have no idea what it does.

      categoryTypeAheadVals: function() {
    cats = Todos.find({}, {categories: 1}).fetch().map(function(it){ return it.categories; });
    y = [];
    var x = cats.forEach(function(it) {
      it.forEach(function(it){
        y.push(it);
      });
    });
    return y;
  }

});
New

This code can actually be further reduced by using JavaScript's apply:

y = y.concat.apply(y, cats);


The above line will merge all the arrays inside the cats array into a single array and then copy it into y.

This is better than the solution you already have because:


It is faster. No more looping over two arrays.
It is easier to read. If you want, just slap a comment on this line and it is very easy to understand.




Old


it.forEach(function(it){
    y.push(it);
});



This section is over-done. All you are doing is copying the array it into y, and JavaScript already has a built in function for that: Array.prototype.concat.

You can use this function to copy one array into another.

Now, your code becomes this:

var x = cats.forEach(function(it) {
    y = y.concat(it);
});