【发布时间】:2016-03-04 08:42:17
【问题描述】:
我有如下数组:
files = [
{name: 'Lorem', other: true},
{name: 'Foo', other: true},
{name: 'Bar', other: true}
];
files = [
{name: 'Lorem', other: true},
{name: 'Xxxxx', other: true}
];
files = [
{name: 'Lorem', other: true},
{name: 'Foo', other: true},
{name: 'Epic', other: true},
{name: 'Xxxxx', other: true}
];
我正在尝试使用带有下划线的独特元素获得一个合并数组,但它不起作用。这是我的代码:
function getAllFiles(alldocs) {
var all = [];
_.each(alldocs, function(element) {
all = _.union(all, element.files);
});
return all;
}
但我得到一个包含重复项的数组。
【问题讨论】:
-
你也可以使用underscorejs.org/#uniq 和
union -
下面给出的解决方案都只检查“名称”属性,但您可能希望区分“名称”和“其他”属性。循环遍历数组并检查两者。如果它只是您要检查的单个值,您可以使用地图并减少单线。
标签: javascript arrays underscore.js unique union