js

数组去重

2017-02-22  本文已影响10人  u14e

Array.prototype.indexOf():

function unique(arr) {
    return arr.filter((item, index) => 
        arr.indexOf(item) === index
    )
}
function unique(arr) {
    let temp = [];
    arr.forEach(item => {
        if (temp.indexOf(item) === -1) {
            temp.push(item);
        }
    });
    return temp;
}

Array.prototype.includes():

function unique(arr) {
    let temp = [];
    arr.forEach(item => {
        if (!temp.includes(item)) {
            temp.push(item);
        }
    });
    return temp;
}

new Set():

function unique(arr) {
    return [...new Set(arr)]
}
上一篇 下一篇

猜你喜欢

热点阅读