Closed azl397985856 closed 3 years ago
a naive implementation
Array.prototype.unique = function unique() {
if (!Array.isArray(this)) {
throw new Error('invalid input')
}
const res = []
const hasIncluded = (list, item) =>
list.some(el => JSON.stringify(el) === JSON.stringify(item))
for (let i = 0; i < this.length; i++) {
hasIncluded(res, this[i]) || res.push(this[i])
}
return res
}
const foo = { a: 1, b: { c: 2 } }
const bar = { a: 1, b: { c: 2 } }
const arr = [foo, bar, 'suukii', 'suukii']
console.log([...new Set(arr)]) // [ { a: 1, b: { c: 2 } }, { a: 1, b: { c: 2 } }, 'suukii' ]
console.log(arr.unique()) // [ { a: 1, b: { c: 2 } }, 'suukii' ]
怎么这么厉害
@suukii 序列化可还行
考虑过函数,正则这些吗,Map,Set?
那要写太多了... I said it's a naive implementation. 放弃思考
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
[...new Set(array)] 只能处理原始类型值,对象等复杂引用类型中的数据因为引用的不同而不适用,就需要一个按一定条件去重的方法
请实现 Array.prototype.unique 方法,接受 Array,能够去重引用类型,即如果引用不同仍然需要判断内部值是否相同。