Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating an array of arrays in Coffeescript

I'm trying to find an elegant way in Coffeescript to merge an array of arrays, so that [[1,2,3],[4,5,6],[7,8,9]] ==> [1,2,3,4,5,6,7,8,9].

As you might imagine, I need this because I'm generating arrays from a function in a "for in" construct and need to concatenate the resulting nested array:

result = (generate_array(x) for x in arr)

Is there an elegant way to handle this? Thanks for any pointers!

like image 337
drcode Avatar asked Jan 08 '11 00:01

drcode


People also ask

How do you concatenate arrays in an array?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How do I concatenate one array to another?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.


2 Answers

Just use the JS idiom:

 [].concat.apply([], a) 

which becomes a little nicer in Coffee:

$ coffee -e 'a = [[1,2,3],[4,5,6],[7,8,9]]; console.dir [].concat a...' [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 
like image 53
matyr Avatar answered Sep 30 '22 08:09

matyr


OK, one way is to include the underscore.js library. It is a very nice, lightweight but powerful utility library, and it has _.flatten which does exactly this.

Barring that, you could take the underscore.js code for flatten and modify it to remove any other underscore dependencies to create your own standalone "flatten".

Here's the underscore.js "_.flatten" code:

 _.flatten = function(array) {
   return _.reduce(array, function(memo, value) {
     if (_.isArray(value)) return memo.concat(_.flatten(value));
     memo[memo.length] = value;
     return memo;
   }, []);
 };

Notice that it is doing some nice stuff for you. For example, many of the underscore functions like _.reduce will check to see if the browser has implemented a native version, which some have. If so, it will use the native which of course runs much faster. The _.isArray implementation does the same thing.

like image 40
Charlie Flowers Avatar answered Sep 30 '22 08:09

Charlie Flowers