Concatenating an array of arrays in Coffeescript

后端 未结 5 716

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 t

相关标签:
5条回答
  • 2021-02-04 00:51

    sugarjs is another elegance way to do it:

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

    sugarjs: flatten

    0 讨论(0)
  • 2021-02-04 00:56

    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 ]
    
    0 讨论(0)
  • 2021-02-04 00:57

    Why not try using Lodash?

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

    https://lodash.com/docs#flatten

    0 讨论(0)
  • 2021-02-04 01:00

    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));
    
    0 讨论(0)
  • 2021-02-04 01:05

    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.

    0 讨论(0)
提交回复
热议问题