-
Notifications
You must be signed in to change notification settings - Fork 0
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
Labels
coding
test or practice
Comments
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;
}, []);
} |
需要加个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);
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]]
The text was updated successfully, but these errors were encountered: