在多个 JavaScript 数组之间查找匹配项 [英] Finding matches between multiple JavaScript Arrays

查看:60
本文介绍了在多个 JavaScript 数组之间查找匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个带有字符串值的数组,我想对它们进行比较,并且只保留 ALL 之间相同的匹配结果.

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.

鉴于此示例代码:

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']

我知道我可以将所有数组与 var newArr = arr1.concat(arr2, arr3); 结合起来,但这只会给我一个包含所有内容的数组,再加上重复项.这是否可以轻松完成而无需 underscore.js 等库的开销?

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!)

编辑我想我应该提到可能有未知数量的数组,我只是以 3 为例.

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;
    });
});

演示: http://jsfiddle.net/nWjcp/2/

你可以先对外面的Array进行排序,得到开头最短的Array...

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;
});

<小时>

为了完整起见,这里有一个处理数组中重复项的解决方案.它使用 .reduce() 而不是 .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;
}, []);

演示: http://jsfiddle.net/nWjcp/4/

这篇关于在多个 JavaScript 数组之间查找匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆