JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
JavaScript
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.
const input3 = [1,2,4,6,true,'4','1','hello','hello',null,undefined,{a:undefined},{b:{a:undefined}},{b:{a:undefined}}]
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(input1));
console.log(deDuplicate(input2));
console.log(deDuplicate(input3));