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

//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 = [...mySet]; // [1, 2, 4]

// 方法3, 传统forEach
var arr2 = [];
mySet.forEach(v => arr2.push(v)); 
复制代码

多维转一维

复制代码
var arr = [1,[2,[[3,4],5],6]];
function unid(arr){
        var arr1 = (arr + '').split(',');//将数组转字符串后再以逗号分隔转为数组
        var arr2 = arr1.map(function(x){
            return Number(x);
        });
        return arr2;
}
console.log(unid(arr));
复制代码

猜你喜欢

转载自www.cnblogs.com/mahmud/p/10349871.html