uniqWith
2024年06月17日
一、认识
二、语法
三、实现
3.1 reduce
function uniqWith(array, comparator) {
return array.reduce((prev, curr) => {
return prev.concat(prev.some((item) => comparator(curr, item)) ? [] : curr);
}, []);
}
function isObject(value) {
return typeof value === "object" && value !== null;
}
function isEqual(value, other) {
if (!isObject(value) || !isObject(other)) {
return value === other;
}
const valueKeys = Object.keys(value);
const otherKeys = Object.keys(other);
if (valueKeys.length !== otherKeys.length) {
return false;
}
for (let key in value) {
if (!isEqual(value[key], other[key])) {
return false;
}
}
return true;
}
console.log(uniqWith([1, 2, { x: 1, y: 2 }, 1, 2, { y: 2, x: 1 }], isEqual));