查找多个JavaScript阵列之间的匹配 [英] Finding matches between multiple JavaScript Arrays

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

问题描述

我有一个字符串值多个阵列,我想对它们进行比较,并只保留匹配的结果是全部他们。

之间是相同的

由于这个例子code:

  VAR ARR1 = ['苹果','橙','香蕉','鸭梨','鱼','煎饼','炸玉米饼','比萨'];
VAR ARR2 = ['炸玉米饼','鱼','苹果','比萨'];
VAR ARR3 = ['香蕉','比萨','鱼','苹果'];

我想生成以下数组包含所有给定的数组匹配:

  ['苹果','鱼','比萨']

我知道我可以用 VAR newArr = arr1.concat(ARR2,ARR3)所有的阵列组合; 但只是给我的一切阵列,再加上重复。可以这样无需库的开销,如underscore.js容易做到?

(大和的现在的我也饿了!)

修改我想我应该指出,有可能是一个数组的未知量,我只是用3作为一个例子。


解决方案

  VAR的结果= arrays.shift()。过滤器(函数(五){
    返回arrays.every(函数(){
        返回a.indexOf(V)== -1!;
    });
});

DEMO: http://jsfiddle.net/nWjcp/2/

您可以先进行排序外阵列之初获得最短的阵列...

  arrays.sort(功能(A,B){
    返回则为a.length - b.length个;
});


有关完整性,这里是与数组中的重复交易的解决方案。它采用。降低()而不是 .filter() ...

  VAR的结果= arrays.shift()。降低(功能(RES,V){
    如果(res.indexOf(ⅴ)=== -1放大器;&放大器; arrays.every(功能(一){
        返回a.indexOf(V)== -1!;
    }))res.push(ⅴ);
    返回水库;
},[]);

DEMO: http://jsfiddle.net/nWjcp/4/

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阵列之间的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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