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]數組

差集:this

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

並集:prototype

var tempArr = a.slice() ;code

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

交集:blog

a.filter(v => b.includes(v))字符串

去重input

方法一:it

   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));
相關文章
相關標籤/搜索