删除数组中的重复元素,并返回被删除元素的数组

Array.prototype.removeDuplicateItem = function () {
    let arr = Object.assign([],this);
    const map = new Map();
    arr.filter((item, index) => { return !map.has(item) && map.set(item, index) });//用map存非重复元素及它的下标
    let uniqueIndexList = [...map.values()];//非重复元素的下标
    const res = arr.filter((item, index) => !(uniqueIndexList.includes(index)));
    arr.forEach((item, index) => {
        if (!uniqueIndexList.includes(index)) {//将重复的元素移动到最后,把原来的位置置空
            this[index] = null;
            this.push(item);
        }
    })
    this.splice(arr.length)//删除重复的元素
    for (let i = 0; i < this.length; i++){//删除null值
        if (this[i] === null) {
            this.splice(i, 1);
            i--;
        }
    }
    return res
}

let arr = new Array(1, 3, 4, 4, 4, 5, 6, 7, 8, 7, 9, 3, 5, 6, 0);
arr.removeDuplicateItem()//[ 4, 4, 7, 3, 5, 6 ]
console.log(arr)//[ 1, 3, 4, 5, 6, 7, 8, 9, 0 ]

你可能感兴趣的:(删除数组中的重复元素,并返回被删除元素的数组)