如何使用下划线的链方法返回多维数组中的第一项?

Chr*_*tta 10 javascript chaining chain underscore.js

假设我有一个数组数组,我想返回数组中每个数组的第一个元素:

array = [[["028A","028B","028C","028D","028E"],
          ["028F","0290","0291","0292","0293"],
          ["0294","0295","0296","0297","0298"],
          ["0299","029A","029B","029C","029D"],
          ["029E","029F","02A0","02A1","02A2"]],
         [["02A3","02A4"],
          ["02A5", "02A6"]];
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

var firsts = [];
_.each(array, function(item){
  _.each(item, function(thisitem){
    firsts.push(_.first(thisitem));
  });
});
Run Code Online (Sandbox Code Playgroud)

但是,如果我想用下划线的_.chain()方法做什么呢?只是学习下划线,到目前为止似乎非常有用.

mu *_*ort 30

你可以这样做flatten,map因此:

var firsts = _.chain(array)
              .flatten(true) // This true is important.
              .map(function(a) { return a[0] })
              .value();
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/cm3CJ/

您可以使用flatten(true)将数组数组转换为数组数组,然后map剥离每个内部数组的第一个元素.

如果你想要比它更短的东西map,你可以pluck用来拉出内部数组的第一个元素:

var firsts = _.chain(array)
              .flatten(true) // This true is important.
              .pluck(0)
              .value();
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/pM9Hq/

_.pluckmap无论如何只是一个电话:

// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
  return _.map(obj, function(value){ return value[key]; });
};
Run Code Online (Sandbox Code Playgroud)

这个看起来更像.map(&:first)是你在Ruby中使用的,所以它可能对某些人来说更熟悉,一旦你习惯了就更简洁pluck.如果你真的想要一些Rubyish,你可以使用非匿名函数map:

var first  = function(a) { return a[0] };
var firsts = _.chain(array)
              .flatten(true) // This true is important.
              .map(first)
              .value();
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,我发现使用**pluck**非常有趣.它为提取_seconds_,_thirds_等提供了方法.从一开始就使用**下划线**的Rubish解决方案可以使用以下代码作为第一行:`var first = function(a){return _.first(a); };` (2认同)