1、方法一(常规for循环)
两个数组进行for循环嵌套,然后判断元素是否相等,如果相等就push到新的数组中。
let arr1 = [1, 2, 3, 4, 5]
let arr2 = [4, 5, 6, 7, 8]
let intersection = []
for (let i = 0; i < arr1.length; i ) {
for (let j = 0; j < arr2.length; j ) {
if (arr1[i] === arr2[j]) {
intersection.push(arr1[i])
}
}
}
console.log(intersection) // [4, 5]
方法二(使用ES6的filter函数和includes函数)
let arr1 = [1, 2, 3, 4, 5]
let arr2 = [4, 5, 6, 7, 8]
console.log(arr1.filter((item) => arr2.includes(item))) // [4, 5]
方法三(reduce)
先合并和排序,然后通过reduce参数进行对比,判断上一个和当前元素相同时push到新的数组中。
let arr1 = [1, 2, 3, 4, 5]
let arr2 = [4, 5, 6, 7, 8]
let arr = arr1.concat(arr2).sort()
let intersection = []
arr.reduce((pre, now) => {
if (pre === now) {
intersection.push(now)
}
return now
})
console.log(intersection) // [4, 5]
原文出处:http://www.dongblog.com/notes/31.html
来源:博客网 转载请注明出处!