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

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 ]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容