azl397985856 / fe-interview

宇宙最强的前端面试指南 (https://lucifer.ren/fe-interview)
Apache License 2.0
2.83k stars 260 forks source link

【每日一题】- 2020-07-14 - 复杂类型去重 #137

Closed azl397985856 closed 3 years ago

azl397985856 commented 4 years ago

[...new Set(array)] 只能处理原始类型值,对象等复杂引用类型中的数据因为引用的不同而不适用,就需要一个按一定条件去重的方法

请实现 Array.prototype.unique 方法,接受 Array,能够去重引用类型,即如果引用不同仍然需要判断内部值是否相同。

suukii commented 4 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' ]
h123truncate commented 4 years ago

怎么这么厉害

azl397985856 commented 4 years ago

@suukii 序列化可还行

feikerwu commented 4 years ago

考虑过函数,正则这些吗,Map,Set?

suukii commented 4 years ago

那要写太多了... I said it's a naive implementation. 放弃思考

stale[bot] commented 4 years ago

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.