JS数组交集、并集、差集的示例代码
本文介绍了JS数组交集、并集、差集,分享给大家,具体如下:
由于下面会用到ES5的方法,低版本会存在兼容,先应添加对应的polyfill
Array.prototype.indexOf=Array.prototype.indexOf||function(searchElement,fromIndex){
varindex=-1;
fromIndex=fromIndex*1||0;
for(vark=0,length=this.length;k=fromIndex&&this[k]===searchElement){
index=k;
break;
}
}
returnindex;
};
Array.prototype.filter=Array.prototype.filter||function(fn,context){
vararr=[];
if(typeoffn==="function"){
for(vark=0,length=this.length;k
依赖数组去重方法:
//数组去重
Array.prototype.unique=function(){
varn={},r=[];
for(vari=0;i
交集
交集元素由既属于集合A又属于集合B的元素组成
Array.intersect=function(arr1,arr2){
if(Object.prototype.toString.call(arr1)==="[objectArray]"&&Object.prototype.toString.call(arr2)==="[objectArray]"){
returnarr1.filter(function(v){
returnarr2.indexOf(v)!==-1
})
}
}
//使用方式
Array.intersect([1,2,3,4],[3,4,5,6]);//[3,4]
并集
并集元素由集合A和集合B中所有元素去重组成
Array.union=function(arr1,arr2){
if(Object.prototype.toString.call(arr1)==="[objectArray]"&&Object.prototype.toString.call(arr2)==="[objectArray]"){
returnarr1.concat(arr2).unique()
}
}
//使用方式
Array.union([1,2,3,4],[1,3,4,5,6]);//[1,2,3,4,5,6]
差集
A的差集:属于A集合不属于B集合的元素
B的差集:属于B集合不属于A集合的元素
Array.prototype.minus=function(arr){
if(Object.prototype.toString.call(arr)==="[objectArray]"){
varinterArr=Array.intersect(this,arr);//交集数组
returnthis.filter(function(v){
returninterArr.indexOf(v)===-1
})
}
}
//使用方式
vararr=[1,2,3,4];
arr.minus([2,4]);//[1,3]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。