You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function removeDuplicates(arr) {
if (!Array.isArray(arr)) {
return []
}
const set = new Set(arr.map(item => JSON.stringify(item)))
return [...set].map(item => JSON.parse(item))
}
// 返回原数组元素
function removeDuplicates(arr) {
const result = []
if (!Array.isArray(arr)) {
return result
}
const set = new Set()
arr.forEach(item => {
if (!set.has(JSON.stringify(item))) {
set.add(JSON.stringify(item))
result.push(item)
}
})
return result
}
Activity
chengjianguo1 commentedon Dec 8, 2020
shadowkimi520 commentedon Dec 8, 2020
// 不返回原数组元素
function removeDuplicates(arr) { if (!Array.isArray(arr)) { return [] } const set = new Set(arr.map(item => JSON.stringify(item))) return [...set].map(item => JSON.parse(item)) }// 返回原数组元素
function removeDuplicates(arr) { const result = [] if (!Array.isArray(arr)) { return result } const set = new Set() arr.forEach(item => { if (!set.has(JSON.stringify(item))) { set.add(JSON.stringify(item)) result.push(item) } }) return result }sisterAn commentedon Dec 9, 2020
解法:使用 JSON.stringify 去重
深入一下
使用
JSON.stringify,如果数组元素是object类型且里面键的顺序不同则会认为是两个不同放入数组元素这种问题该如何解决喃?
解决思路:
一个数组(包含对象等类型元素)去重函数,需要在基础类型判断相等条件下满足以下条件:
去重本身就是遍历数组,然后比较数组中的每一项是否相等而已,所以关键步骤有两步:比较、去重
比较:
===比较去重:
reduce去重,初始accumulator为[]findIndex找到accumulator是否包含相同元素,如果不包含则加入,否则不加入accumulator,则为去重后的数组代码实现: