Last active
February 3, 2022 17:28
-
-
Save edsoliman/201706602bcad2ba86b0048ba33cb159 to your computer and use it in GitHub Desktop.
Remove duplicates from array - all data types with shallow objects only.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {{[key: string]: number}} obj1 | |
* @param {{[key: string]: number}} obj2 | |
* @return {boolean} equal - Are the two objects equal? | |
*/ | |
const shallowCompare = (obj1, obj2) => { | |
// If passing in undefined values, this means the obj did not exist in the dupsHash in removeDuplicates(), so return. | |
if (typeof obj1 !== 'object' || typeof obj2 !== 'object') return; | |
const obj1Keys = Object.keys(obj1); | |
const obj2Keys = Object.keys(obj2); | |
if (obj1Keys.length !== obj2Keys.length) return; | |
let equal = true; | |
obj1Keys.forEach(key => { | |
// If at any point obj1[key] is not defined on obj2[key], return so as to not loop unecessarily. | |
if (!equal) return; | |
obj1[key] === obj2[key] ? equal = true : equal = false; | |
}) | |
return equal; | |
} | |
/** | |
* @param {mixed[]} arr | |
* @return {mixed[]} removedDupsArr - An array with all duplicates removed | |
*/ | |
const removeDuplicates = (arr) => { | |
const removedDupsArr = []; | |
const dupsHash = {}; | |
for (let i = 0; i < arr.length; i++) { | |
const isObj = typeof arr[i] === 'object'; | |
if (isObj) var objStrKey = JSON.stringify(arr[i]); | |
if (isObj ? !shallowCompare(arr[i], dupsHash[objStrKey]) : !dupsHash[arr[i]]) { | |
isObj ? dupsHash[objStrKey] = arr[i] : dupsHash[arr[i]] = true; | |
removedDupsArr.push(arr[i]); | |
} | |
} | |
return removedDupsArr; | |
}; | |
removeDuplicates( | |
[[1, 2], [1, 2], [1, 3], {hello: 'world', righteous: 'dude'}, {hello: 'world', righteous: 'dude'}, {hello: 'world'}, 1, 45, 1, 66, 66, 66, 'e', 'e'] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment