假设我有一个嵌套的数组结构。
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; });但是,这种方法不适用于下划线的map函数。
那么如何使用underscore.js获得扁平化的数组[1, 2, 3]呢?
发布于 2012-09-10 08:13:01
var nested = [ [1], [2], [3] ];
var flattened = _.flatten(nested);这是一个fiddle
发布于 2014-08-05 03:28:16
如果您有一个稍微复杂一点的数组,比如一个来自JSON的数组,您也可以利用pluck方法,提取您感兴趣的特定属性,类似于parents.SelectMany(parent => parent.Items);
// underscore version
var allitems = _.flatten(_.pluck(parents, 'items'));allitems现在是来自父级[a,b,c,d]的所有子项的数组。
和一个显示相同内容的JSFiddle。
或者,如果你正在使用lodash,你可以通过使用_.flatMap函数来做同样的事情,这个函数从版本4.cred到Noel,因为它在注释中指出了它。
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>
发布于 2016-05-19 04:39:43
我们也可以把Patrick's solution做成一个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 ]https://stackoverflow.com/questions/12344007
复制相似问题