zoukankan      html  css  js  c++  java
  • 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));
  • 相关阅读:
    团队作业开发过程
    UVM基础之--------uvm_root
    UVM基础之------uvm_transaction
    UVM基础之----uvm_object
    UVM挑战及概述
    定制UVM Messages(参考)
    SV creation order
    IC验证概念总结
    win7 硬盘安装suse双系统启动顺序更改
    suse 下的gcc安装
  • 原文地址:https://www.cnblogs.com/liujinyu/p/7095046.html
Copyright © 2011-2022 走看看