Finding matches between multiple JavaScript Arrays(查找多个 JavaScript 数组之间的匹配项)
问题描述
I have multiple arrays with string values and I want to compare them and only keep the matching results that are identical between ALL of them.
Given this example code:
var arr1 = ['apple', 'orange', 'banana', 'pear', 'fish', 'pancake', 'taco', 'pizza'];
var arr2 = ['taco', 'fish', 'apple', 'pizza'];
var arr3 = ['banana', 'pizza', 'fish', 'apple'];
I would like to to produce the following array that contains matches from all given arrays:
['apple', 'fish', 'pizza']
I know I can combine all the arrays with var newArr = arr1.concat(arr2, arr3);
but that just give me an array with everything, plus the duplicates. Can this be done easily without needing the overhead of libraries such as underscore.js?
(Great, and now i'm hungry too!)
EDIT I suppose I should mention that there could be an unknown amount of arrays, I was just using 3 as an example.
var result = arrays.shift().filter(function(v) {
return arrays.every(function(a) {
return a.indexOf(v) !== -1;
});
});
DEMO: http://jsfiddle.net/nWjcp/2/
You could first sort the outer Array to get the shortest Array at the beginning...
arrays.sort(function(a, b) {
return a.length - b.length;
});
For completeness, here's a solution that deals with duplicates in the Arrays. It uses .reduce()
instead of .filter()
...
var result = arrays.shift().reduce(function(res, v) {
if (res.indexOf(v) === -1 && arrays.every(function(a) {
return a.indexOf(v) !== -1;
})) res.push(v);
return res;
}, []);
DEMO: http://jsfiddle.net/nWjcp/4/
这篇关于查找多个 JavaScript 数组之间的匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查找多个 JavaScript 数组之间的匹配项
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01