JavaScript获取两个数组数组的差集
JavaScript在ES6中增加了很多Array对象的方法,这让我们在做数组元素操作的时候方便很多。
以下便是分别通过Array的some,find,findIndex和includes方法配合filter实现的两个数组的差集的方式,和测试结果:
const arra = ['a', 'b', 'c', 'd', 'e'];
const arrb = ['b', 'e'];
console.log("some: " + arra.filter(v => !arrb.some((item) => item === v)));
console.log("find: " + arra.filter(v => !arrb.find((item) => item === v)));
console.log("findIndex: " + arra.filter(v => arrb.findIndex((item) => item === v) < 0));
console.log("includes: " + arra.filter(v => !arrb.includes(v)));
console.log(arra);
运行结果:
some: a,c,d
find: a,c,d
findIndex: a,c,d
includes: a,c,d
(5)['a','b','c','d','e']
该方法返回新数组,不改变原数组的内容。
抽象成方法(仅提供includes的方式,其他方式直接替换即可):
function arrayAminusB(arrA, arrB) {
return arrA.filter(v => !arrB.includes(v));
}
————————————————
https://blog.csdn.net/tonglei85/article/details/109615333
标签:arrb,arra,JavaScript,差集,includes,filter,item,数组 From: https://www.cnblogs.com/linhan8888/p/16812488.html