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

数组去重 #12

Open
yijinc opened this issue Aug 20, 2021 · 2 comments
Open

数组去重 #12

yijinc opened this issue Aug 20, 2021 · 2 comments
Labels
coding test or practice

Comments

@yijinc
Copy link
Owner

yijinc commented Aug 20, 2021

example

  • 输入:[1,'1',1], 则输出: [1,'1']
  • 输入:[{a: 1}, {b: 1}, {a: 1}], 则输出:[{a: 1}, {b: 1}]
  • 输入:[{a: 1}, {b: 1}, {a: 1}], 则输出:[{a: 1}, {b: 1}]
  • 输入:[{a: 1, b: 2}, {b: 1}, {b: 2, a: 1}], 则输出:[{a: 1, b: 2}, {b: 1}]
  • 输入:[[1, {a: 1}], [2], [3], [1, {a: 1}]], 则输出: [[1, {a: 1}], [2], [3]]
@yijinc yijinc changed the title Coding:数组去重复 Coding:数组去重 Aug 20, 2021
@yijinc
Copy link
Owner Author

yijinc commented Aug 20, 2021

function unique(arr) {
    const isEqual = (a, b) => {
        if (Array.isArray(a) && Array.isArray(b)) {
            return a.every((item, index) => isEqual(item, b[index]));
        }
        if (typeof a === 'object' && typeof b === 'object') {
            return Object.keys(a).every((key) => isEqual(a[key], b[key]));
        }
        return Object.is(a, b);
    };
    return arr.reduce((accumulator, current) => {
        if (accumulator.findIndex(item => isEqual(current, item)) === -1) {
            accumulator.push(current);
        }
        return accumulator;
    }, []);
}

@yijinc yijinc added the coding test or practice label Aug 20, 2021
@yijinc
Copy link
Owner Author

yijinc commented Aug 31, 2021

    const isEqual = (a, b) => {
        if (Array.isArray(a) && Array.isArray(b)) {
            return a.every((item, index) => isEqual(item, b[index]));
        }
        if (typeof a === 'object' && typeof b === 'object') {
            return Object.keys(a).every((key) => isEqual(a[key], b[key]));
        }
        return Object.is(a, b);
    };

isEqual 的判断有问题,当第二个变量多于第一个时,判断出错,如
isEqual([0, 1], [0, 1, 2]) === true

需要加个length 先判断

const isEqual = (a, b) => {
        if (Array.isArray(a) && Array.isArray(b)) {
            return a.length === b.length ? a.every((item, index) => isEqual(item, b[index])) : false;
        }
        if (typeof a === 'object' && typeof b === 'object') {
            return Object.keys(a).length === Object.keys(b).length ? Object.keys(a).every((key) => isEqual(a[key], b[key])) : false;
        }
        return Object.is(a, b);
};

@yijinc yijinc changed the title Coding:数组去重 数组去重 Jun 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
coding test or practice
Projects
None yet
Development

No branches or pull requests

1 participant