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

查看:42
本文介绍了在 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

如何找到两个数组共有的值?在这种情况下,应该返回 "sue""kathy".

How can I find the values common to both arrays? In this case "sue" and "kathy" should be returned.

推荐答案

这里是一个基于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) {
        return b.indexOf(e) > -1;
    });
}

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

上面现在将给出 ["sue", "sue", "kathy"].如果您不想重复,您可以对此进行进一步过滤.这也将标准化结果.即

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

现在添加这个将返回与之前数组相同的结果(["sue", "kathy"]),即使有重复.

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

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

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