수조 다중 제거 방식

1561 단어

1. Set

Array.prototype.unique = function() {
    return [...new Set(this)];
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique(); //[1, 2, 3, 43, 45, 4, 5]

2. Map

Array.prototype.unique = function() {
    const tmp = new Map();
    return this.filter(item => {
        return !tmp.has(item) && tmp.set(item, 1);
    })
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique(); //[1, 2, 3, 43, 45, 4, 5]

3. Array.prototype.indexOf()

Array.prototype.unique = function() {
    return this.filter((item, index) => {
        return this.indexOf(item) === index;
    })
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique(); //[1, 2, 3, 43, 45, 4, 5]

4.Array.prototype.includes()

Array.prototype.unique = function() {
    const newArray = [];
    this.forEach(item => {
        if (!newArray.includes(item)) {
            newArray.push(item);
        }
    });
    return newArray;
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique(); //[1, 2, 3, 43, 45, 4, 5]

5. Array.prototype.reduce()

Array.prototype.unique = function() {
    return this.sort().reduce((init, current) => {
        if (init.length === 0 || init[init.length - 1] !== current) {
            init.push(current);
        }
        return init;
    }, []);
}
var array = [1, 2, 3, 43, 45, 1, 2, 2, 4, 5];
array.unique(); //[1, 2, 3, 43, 45, 4, 5]

좋은 웹페이지 즐겨찾기