include lodash https://cdnjs.com/libraries/lodash.js or https://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));
input1 - [ 1, 2, 4, 6, { a: 1 } ]
input2 - [ 1, 2, 4, 6, { a: undefined }, { b: undefined } ]
live example https://jsfiddle.net/9cx4kget/
JSON.stringify()removes keys withundefined,functionand other invalid values in a JSON string.JSON.stringify({ a:undefined })is "{}"`JSON.stringify(Object.entries(value))for objects if you are not concerned about the order of the keys in the object or null and undefined being treated as same.