在JavaScript中两个数组的交集计算 [英] Compute intersection of two arrays in JavaScript

查看:107
本文介绍了在JavaScript中两个数组的交集计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于不等长的两个数组:

Given two arrays of unequal length:

var arr1 = ["mike", "sue", "tom", "kathy", "henry"]; //arr1.length = 5
var arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"]; //arr2.length = 7

我怎样才能找到共同的价值观念,以两个阵列?在这种情况下起诉凯西应返回。

推荐答案

下面是一个基于<一个路口功能href=\"https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array/filter\"><$c$c>Array.prototype.filter

Here is an intersection function based on Array.prototype.filter

function intersect(a, b) {
    var t;
    if (b.length > a.length) t = b, b = a, a = t; // indexOf to loop over shorter
    return a.filter(function (e) {
        if (b.indexOf(e) !== -1) return true;
    });
}

var arr1 = ["mike", "sue", "tom", "kathy", "henry"];
    arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"];

intersect(arr1, arr2); // ["sue", "kathy"]


您可能还需要考虑以下


You might also want to consider the following

var arr1 = ['sue', 'sue', 'kathy'],
    arr2 = ['kathy', 'kathy', 'sue'];

以上现在会给 [起诉,苏,凯西] 。如果你不想重复,你可以做这样一个进一步过滤。这也将标准化的结果。即。

The above would now give ["sue", "sue", "kathy"]. If you don't want duplicates you could do a further filter on this. This would also standardise results. i.e.

return a
    .filter(/* .. */) // same as before
    .filter(function (e, i, c) { // extra step to remove duplicates
        return c.indexOf(e) === i;
    });

添加此现在将返回相同的结果previous阵列( [起诉,凯西] ),即使有重复。

Adding this will now return the same result as the previous arrays (["sue", "kathy"]), even though there were duplicates.

这篇关于在JavaScript中两个数组的交集计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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