javascript中数组交集的最简单代码 [英] Simplest code for array intersection in javascript

查看:31
本文介绍了javascript中数组交集的最简单代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 javascript 中实现数组交集的最简单、无需库的代码是什么?我要写

What's the simplest, library-free code for implementing array intersections in javascript? I want to write

intersection([1,2,3], [2,3,4,5])

并得到

[2, 3]

推荐答案

使用Array.prototype.filterArray.prototype.includes:

const filteredArray = array1.filter(value => array2.includes(value));

对于较旧的浏览器,使用 Array.prototype.indexOf 并且没有箭头函数:

For older browsers, with Array.prototype.indexOf and without an arrow function:

var filteredArray = array1.filter(function(n) {
    return array2.indexOf(n) !== -1;
});

注意!.includes.indexOf 都使用 === 在内部比较数组中的元素,所以如果数组包含对象,它只会比较对象参考文献(不是它们的内容).如果要指定自己的比较逻辑,请使用 Array.prototype.some 代替.

NB! Both .includes and .indexOf internally compares elements in the array by using ===, so if the array contains objects it will only compare object references (not their content). If you want to specify your own comparison logic, use Array.prototype.some instead.

这篇关于javascript中数组交集的最简单代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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