如何在数组列表中找到公共元素
How can I find the common elements in a list of arrays?
a = [1, 2, 3, 4, 5]
b = [1, 3, 6, 4, 5, 9]
c = [5, 4, 7, 9]
d = [1, 7, 5, 6, 9, 4]
e = [4, 3, 5, 7, 1]
f = [...]
.
.
(n = [n,n,n])
对于许多情况下的 1 种,我们有 5 个从 a 到 e 的变量,我们希望从这 5 个数组中获取交集元素,而不必编写嵌套 for.。每种情况的循环。
请提出此问题的理想解决方案。
首先找到第一个数组和第二个数组之间的公共元素,然后找到前一组公共元素和第三个数组之间的公共元素,依此类推。
var listOfArrays = [a, b, c, d, e, ...];
var commons = listOfArrays.slice(1).reduce(function(result, currentArray) {
return currentArray.filter(function(currentItem) {
return result.indexOf(currentItem) !== -1;
});
}, listOfArrays[0]);
这里
currentArray.filter(function(currentItem) {...});
是负责查找两个数组之间的公共元素的函数,result
和currentArray
。
我们使用Array.prototype.reduce
,其中传递给它的函数返回的值将在下一次迭代中反馈给同一函数。因此,我们继续将上一次迭代中的常见元素提供给下一次迭代。
这是非Mr.Fancy-Pants版本的:)
function findIntersection() {
// turns the list of arguments into an array
var args = Array.prototype.slice.call(arguments);
// concatenate all the arrays
var all = args.reduce(function (a, b) { return a.concat(b); });
// use the temporary object to store the number of times a
// number appears
for (var i = 0, obj = {}, l = all.length; i < l; i++) {
var key = all[i];
if (!obj[key]) obj[key] = 0;
obj[key]++;
}
// return those numbers that have a value matching the number
// of arguments passed into the function
return Object.keys(obj).filter(function (el) {
return obj[el] === args.length;
}).map(Number);
}
findIntersection(a,b,c,d,e); // [ "4", "5" ]
演示
相关文章:
- 在函数中添加数组元素的数值
- 访问JSON对象内部的数组元素
- 用于检查数组中是否存在元素的javascript自定义方法
- 在数组中的一个元素上设置多个值
- 从组件状态的数组中删除元素
- Mongoose-在更新中删除数组元素
- 从数组中删除元素的最佳方法是:javascript/jquery
- 数组中元素(字符串)的总和
- javascript数组元素是否知道其封闭数组
- 查找数组javascript中包含的元素类型
- 如何在javascript上向数组的对象添加新元素
- 如果数组仍在执行,async.forEach()将运行我添加到数组中的新元素
- 使用filter和map方法将数组中某些元素的第一个字母大写-JavaScript
- 一些元素没有从数组中删除
- JS.循环遍历多维数组,以计数元素在每列中的出现次数
- 将数组元素附加到FormData dos'不适用于Firefox 15
- 元素不会添加到Javascript数组中
- 如何从另一个带下划线的数组中筛选带元素的数组
- 如何将函数应用于两个数组的第 n 个元素(数组的数组)
- Js接受两个值之间的元素(数组)