我正在使用lodash在javascript中做一个数组交集,下面是我正在尝试的代码,我得到的是
["universal", "ola", "uber", "bangalore"],
但是,我期待的是["普遍"]
这里,orgArr具有n个项目的多维数组,我的意思是,orgArr可以有5个或6个或10个项目…示例
[["garden","canons","philips","universal"],["universal","ola","uber","bangalore"], ["ola","uber","bangalore"]];
不只是两个项目请注意
var orgArr = [["garden","canons","philips","universal"],["universal","ola","uber","bangalore"]];
var resfinaArray = [];
for (var i = 0; i < orgArr.length; i++){
var currItem = orgArr[i];
for (var j = 0; j< orgArr.length; j++){
resfinaArray.push(_.intersection(currItem, orgArr[j]));
}
}
console.log(resfinaArray, 'resfinaArray');
请帮忙好吗?
您可以使用forEach()
循环和可选的thisArg
参数。
var orgArr = [["garden","canons","philips","universal"],["universal","ola","uber","bangalore"]];
var resfinaArray = [];
orgArr.forEach(function(a) {
var that = this;
a.forEach(function(e) {
(!that[e]) ? that[e] = true : resfinaArray.push(e);
})
}, {});
console.log(resfinaArray);
我将按以下方法做这项工作;
var intersectArrays = a => a.reduce((p,c) => p.filter(e => c.includes(e))),
arr = [["garden","canons","philips","universal"],["universal","ola","uber","bangalore"], ["ola","uber","bangalore", "universal"]],
brr = intersectArrays(arr);
console.log(brr);
对于ES6,您可以使用Set
和Array#reduce
。
var array = [["garden", "canons", "philips", "universal"], ["universal", "ola", "uber", "bangalore"], ["abc", "def", "universal"]],
result = [...array.reduce((r, a, i) =>
a.reduce((s, b) =>
(!i || r.has(b)) && s.add(b) || s, new Set), new Set)];
console.log(result);
你不需要循环:
var intersection = _.intersection(["garden","canons","philips","universal"],["universal","ola","uber","bangalore"]);
如果你有你的数据在数组中,你可以使用apply
:
var intersection = _.intersection.apply(null, [["garden","canons","philips","universal"],["universal","ola","uber","bangalore"]]);