Question

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!

Was it helpful?

Solution

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 ]

OTHER TIPS

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.

What about this for Coffee

[[1, 2, 3], [4, 5, 6], [7, 8, 9]].reduce (a, b) ->
  a.concat b

or this for pure Javascript

[[1, 2, 3], [4, 5, 6], [7 , 8, 9]].reduce((a, b) => a.concat(b));

sugarjs is another elegance way to do it:

[[1, 2, 3]].flatten() //=> [1, 2, 3]

sugarjs: flatten

Why not try using Lodash?

_.flatten([1,2,3], [4,5,6]) => [1,2,3,4,5,6]

https://lodash.com/docs#flatten

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top