评论

数组去重常用方法

数组去重

function DuplicateRemovalArray_1(arr) {


    var resultArr;
    resultArr = arr.filter(function (item, index, array) {
        return array.indexOf(item) == index;
    });
    return resultArr;
}


 


function DuplicateRemovalArray_2(arr) {


    /**


     *     Accumulator (acc) (累计器)


            Current Value (cur) (当前值)


            Current Index (idx) (当前索引)


            Source Array (src) (源数组)


     * 
     */
    let result = arr.sort().reduce((accumulator, currentValue, currentIndex, array) => {


        if (accumulator.length === 0 || accumulator[accumulator.length - 1] !== currentValue) {


            accumulator.push(currentValue);


        }


        return accumulator;


    }, []);
    return result;


}


 
function DuplicateRemovalArray_3(arr) {
    let mapArray = Array.from(new Set(arr));
    return mapArray;
}



 
function DuplicateRemovalArray_4(arr) {
    let mapArray = [...new Set(arr)]
    return mapArray;
}




let p1 = DuplicateRemovalArray_1([1,2,2,3]);
let p2 = DuplicateRemovalArray_2([3,2,6,6,6,3]);
let p3 = DuplicateRemovalArray_3([1,1,0,1,5]);
let p4 = DuplicateRemovalArray_4([1,1,0,1,5]);


 
console.log(p1);
console.log(p2);
console.log(p3);
console.log(p4);


let Channel = [
    {
        "key": "其他",
        "Count": 1638,
        "Ratio": "2.939300%"
    },
    {
        "key": "其他",
        "Count": 23057,
        "Ratio": "41.374900%"
    },
    {
        "key": "平面",
        "Count": 26674,
        "Ratio": "47.865400%"
    },
    {
        "key": "工程",
        "Count": 32,
        "Ratio": "0.057400%"
    },
];
var obj = {};
let arr = Channel.reduce(function (item, next) {
    obj[next.key] ? '' : obj[next.key] = true && item.push(next);
    return item;
}, []);



console.log(arr);  // 对象去重

输出

[ 1, 2, 3 ]
[ 2, 3, 6 ]
[ 1, 0, 5 ]
[ 1, 0, 5 ]
[
  { key: '其他', Count: 1638, Ratio: '2.939300%' },
  { key: '平面', Count: 26674, Ratio: '47.865400%' },
  { key: '工程', Count: 32, Ratio: '0.057400%' }
]




function uniqueArray(list) {
    
    list.sort()   // [1,101,2,20,21,211,3,1] 注意排序 101 跟  2


    const size = list.length
    let slowP = 0
    for( let fastP = 0; fastP < size; fastP++) {
        if(list[fastP] != list[slowP]) {
            slowP++
            list[slowP] = list[fastP]
        }
    }
    // console.log("slowP", slowP, list)
    return list.slice(0, slowP + 1)
}


let t = uniqueArray([1,101,2,20,21,211,3,1])
t=> [
   1, 101, 2, 20,
  21, 211, 3
]
最后一次编辑于  2022-11-09  
点赞 0
收藏
评论

2 个评论

  • 喵喵队摸大鱼
    喵喵队摸大鱼
    2022-06-14

    可以可以

    2022-06-14
    赞同
    回复
  • 小明🐵
    小明🐵
    2019-09-06

    牛逼

    2019-09-06
    赞同
    回复
登录 后发表内容