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

How do you use underscore's chain method to return the first item in a multidimensional array?

本文关键字:一项 数组 下划线 何使用 方法 返回      更新时间:2023-09-26

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

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"]];

我知道我可以做这样的事情:

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

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

你可以

flatten来做到这一点,map这样:

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

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

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

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

var firsts = _.chain(array)
              .flatten(true) // This true is important.
              .pluck(0)
              .value();

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

无论如何,_.pluck只是一个map电话:

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

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

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