您的位置:首页 > Web前端 > JavaScript

js 数组 : 差集、并集、交集、去重

2017-06-29 16:09 561 查看
//input:[{name:'liujinyu'},{name:'noah'}]
//output:['liujinyu','noah']

Array.prototype.choose = function(key){
var tempArr = [];
this.forEach(function(v){
tempArr.push(v[key])
});
return tempArr;
}


//并集
//[1,2,3].union([3,4])   output:[1,2,3,4]
Array.prototype.union = function(arr){
var tempArr = this.slice();
arr.forEach(function(v) {
!tempArr.includes(v) && tempArr.push(v)
});
return tempArr;
}


a = [1,2,3] ; b = [3,4]

差集:

a.concat(b).filter(v => a.includes(v) ^ b.includes(v)) // [1,2,4]

并集:

var tempArr = a.slice() ;

b.forEach(v => {!tempArr.includes(v) && tempArr.push(v)}) //tempArr=[1,2,3,4]

交集:

a.filter(v => b.includes(v))

去重

方法一:

var tempArr = [] ;

arr.filter(v=>tempArr.includes(v)?false:tempArr.push(v))

方法二:

var arr = [1, 2, 2, 4, 4];
// 使用Set将重复的去掉,然后将set对象转变为数组
var mySet = new Set(arr); // mySet {1, 2, 4}

// 方法1,使用Array.from转变为数组
// var arr = Array.from(mySet); // [1, 2, 4]

// 方法2,使用spread操作符
var arr = [...arr]; // [1, 2, 4]

// 方法3, 传统forEach
var arr2 = [];
mySet.forEach(v => arr2.push(v));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: