什么's是相当于LINQ's SelectMany运算符

What's the underscore.js equivalent to LINQ's SelectMany operator?

本文关键字:SelectMany 运算符 LINQ 相当于 什么      更新时间:2023-09-26

想象一下我有一个嵌套的数组结构。

var nested = [ [1], [2], [3] ];

使用underscore.js,我将如何生成一个扁平的数组?

在C#中,您可以像这样使用Enumerable.SelectMany

var flattened = nested.SelectMany(item => item);

请注意,本例中的lambda直接选择嵌套项,但它可以是任意表达式。

在jQuery中,可以只使用:

var flattened = $.map(nested, function(item) { return item; });

然而,这种方法不适用于下划线的映射函数。

那么,如何使用underscore.js获得扁平数组[1, 2, 3]呢?

如果你有一个稍微复杂一点的数组,比如来自JSON的数组,你也可以利用pulture方法,提取你感兴趣的特定属性,类似于parents.SelectMany(parent => parent.Items);

// underscore version
var allitems = _.flatten(_.pluck(parents, 'items'));

allitems现在是来自父项[a,b,c,d]的所有子项的数组。

还有一个JSFiddle展示了同样的东西。


或者,如果你正在使用lodash,你可以通过使用_.flatMap函数来做同样的事情,该函数从版本4开始就可用了。感谢诺埃尔在评论中指出了这一点。

var parents = [
  { name: 'hello', items: ['a', 'b'] },
  { name: 'world', items: ['c', 'd'] }
];
// version 1 of lodash, straight up
var allitems = _.flatMap(parents, 'items');
logIt('straight', allitems);
// or by wrapping the collection first
var allitems = _(parents)
  .flatMap('items')
  .value();
logIt('wrapped', allitems);
// this basically does _(parents).map('items').flatten().value();
function logIt(wat, value) {
  console.log(wat, value)
}
<script src="https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js"></script>
<pre id="result"></pre>


如果你想做更多的事情,又不想连锁运算符,你可以使用flow函数来获得同样的效果。如果您使用TypeScript并单独导入每个运算符,这将非常有用,因为您可以优化最终负载。

const parents = [
  { name: 'hello', items: ['a', 'b'] },
  { name: 'world', items: ['c', 'd'] }
];
logIt('original', parents);
const result = _.flow(
  (collection) => _.flatMap(collection, (item) => item.items),
  (flattened) => flattened.filter((item) => item !== 'd')
)(parents);
logIt('result without "d"', result);
function logIt(wat, value) {
  console.log(wat, value);
}
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<pre id="result"></pre>

var nested = [ [1], [2], [3] ];
var flattened = _.flatten(nested);

这是一个小提琴

我们还可以将Patrick的解决方案制作成一个mixin,使其成为可链接的:

_.mixin({
    selectMany: function(collection, iteratee=_.identity) {
        return _.flatten(_.map(collection, iteratee));
    }
});

示例:

let sample = [{a:[1,2],b:'x'},{a:[3,4],b:'y'}];
console.log(_.selectMany(sample, 'a')); // [ 1, 2, 3, 4 ]
console.log(_.chain(sample).selectMany(o => o.a).filter(a => a % 2 === 0).map(a => a * 3).value()); // [ 6, 12 ]

我在lodash中找不到任何类似SelectMany的方法,所以我使用纯JS:创建了一个

Array.prototype.selectMany = function(fn) {
    return Array.prototype.concat(...this.map(fn));
};

轰。

> console.log([{a:[1,2],b:'x'},{a:[3,4],b:'y'}].selectMany(o => o.a));
[ 1, 2, 3, 4 ]