gpt4 book ai didi

javascript - 如何从数组中删除重复值?当数组中的对象属性未定义时,我的代码失败

转载 作者:行者123 更新时间:2023-12-04 00:50:15 25 4
gpt4 key购买 nike

我期待一个通用的解决方案,包括高阶对象作为数组的一个元素。

const input1 = [1,2,4,6,'4','1',{a:1},{a:1}]; //my code works
const input2 = [1,2,4,6,'4','1',{a:undefined},{b:undefined}]; //my code fails.

function deDuplicate(arr) {
let obj = {};
arr.forEach(value => {
if (!obj[JSON.stringify(value) + typeof value]) obj[JSON.stringify(value) + typeof value] = value;
});
return Object.values(obj);
}

console.log(deDuplicate(input2));

最佳答案

包括lodash https://cdnjs.com/libraries/lodash.jshttps://www.jsdelivr.com/package/npm/lodash

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

const input1 = [1,2,4,6,'4','1',{a:1},{a:1}]; //my code works
const input2 = [1,2,4,6,'4','1',{a:undefined},{b:undefined}]; //my code fails.

function deDuplicate(arr) {
let res = []
for(const el of arr) {
const dublicateIndex = res.findIndex( (el2) => {

// if both nulls
if( _.isNull(el) && _.isNull(el2) ) {
return true
}

// if both undefined
if( _.isUndefined(el) && _.isUndefined(el2) ) {
return true
}


// check both are string, or numbers
if(
( _.isNumber(el) || _.isString(el)) &&
( _.isNumber(el2) || _.isString(el2) )
) {

return el.toString() === el2.toString()
}

// check if one is object, other not
if(_.isObject(el) !== _.isObject(el2)) {
return false
}

// check both is object
if(_.isObject(el) === _.isObject(el2)) {
return _.isEqual(el, el2)
}

return _.isEqual(el, el2)
})

if(dublicateIndex === -1) {
res.push(el)
}
}
return res
}

console.log(deDuplicate(input3));

输入 1 - [ 1, 2, 4, 6, { a: 1 } ]

input2 - [ 1, 2, 4, 6, {a: undefined }, { b: undefined } ]

实例https://jsfiddle.net/9cx4kget/

关于javascript - 如何从数组中删除重复值?当数组中的对象属性未定义时,我的代码失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67240978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com