JS 数组查重

作者: Cherry丶小丸子 | 来源:发表于2021-09-15 19:39 被阅读0次
    let arr1 = ['a', 'b', 'c', 'd'];
    let arr2 = ['x', 'b', 'c', 'y'];
    let long = arr1.length < arr2.length ? arr2 : arr1;
    let short = arr1.length < arr2.length ? arr1 : arr2;
    let str = "," + long.toString() + ",";
    let result = [];
    for(let i in short){
        if(str.indexOf("," + short[i] + ",") >= 0){
            result.push(short[i]);
        }
    }
    alert(result.toString()); // b, c
    
    
    // 取出两个数组的不同元素
    getArrDifference(arr1, arr2) {
        return arr1.concat(arr2).filter(function(v, i, arr) {
            return arr.indexOf(v) === arr.lastIndexOf(v);
        });
    }
    
    // 取出两个数组的相同元素
    getArrEqual(arr1, arr2) {
        let newArr = [];
        for (let i = 0; i < arr2.length; i++) {
            for (let j = 0; j < arr1.length; j++) {
                if(arr1[j] === arr2[i]){
                    newArr.push(arr1[j]);
                }
            }
        }
        return newArr;
    }
    

    相关文章

      网友评论

        本文标题:JS 数组查重

        本文链接:https://www.haomeiwen.com/subject/zvrlgltx.html