Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现数组去重 #4

Open
TieMuZhen opened this issue Nov 13, 2021 · 0 comments
Open

实现数组去重 #4

TieMuZhen opened this issue Nov 13, 2021 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

实现效果

uniq([1, 2, 3, 5, 3, 2]); // [1, 2, 3, 5]

实现方法

法1: 利用ES6新增数据类型 Set

function uniq (arr) {
    return [...new Set(arr)];
}

法2: 利用 indexOf

function uniq (arr) {
    const result = [];
    for (let value of arr) {
        if (result.indexOf(value) == -1) {
            result.push(value);
        }
    }
    return result;
}

法3: 利用 includes

function uniq (arr) {
    const result = [];
    for (let value of arr) {
        if (!result.includes(value)) {
            result.push(value);
        }
    }
    return result;
}

法4:利用 reduce

function uniq (arr) {
    return arr.reduce((pre, cur) => pre.includes(cur)? pre: [...pre, cur], [])
}

法5:利用 Map

function uniq (arr) {
    const map = new Map()
    const result = [];
    for (let val of arr) {
        if (!map.has(val)) {
            map.set(val, true);
            result.push(val);
        }
    }
    return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant