Skip to content

Instantly share code, notes, and snippets.

@0xAliRaza
Created March 7, 2022 06:05
Show Gist options
  • Save 0xAliRaza/e8299812d08331b651d6b541a28064b8 to your computer and use it in GitHub Desktop.
Save 0xAliRaza/e8299812d08331b651d6b541a28064b8 to your computer and use it in GitHub Desktop.
/**
*
* @param {Object} firstObj
* @param {Object} secondObj
* @return {Boolean}
*/
function checkIfEqualObjects(firstObj, secondObj) {
// Find the keys and their values in both of the objects
const firstArr = Object.entries(firstObj),
secondArr = Object.entries(secondObj);
// Check if both objects have same amount of key/value pairs
if (firstArr.length !== secondArr.length) return false;
// Iterate over first array
for (let i = 0; i < firstArr.length; i++) {
const firstSub = firstArr[i];
// Iterate over second array
for (let j = 0; j < secondArr.length; j++) {
const secondSub = secondArr[j];
if (firstSub[0] === secondSub[0] && firstSub[1] === secondSub[1]) {
// If both sub arrays are equal then break the inner loop
break;
} else if (j === secondArr.length - 1) {
// If no matches were found till the last element then there's no equality
return false;
}
}
}
return true;
}
/**
*
* @param {Array} arr An array of objects
* @return {Array} An array containing unique objects
*/
function removeDuplicates(arr) {
const length = arr.length;
// Iterate over given array
for (let i = 0; i < length; i++) {
// If a duplicate has already been removed from this index then continue
if (arr[i] === null) continue;
// Compare the current objects with objects coming after it
for (let j = i + 1; j < length; j++) {
if (arr[j] === null) continue;
if (checkIfEqualObjects(arr[i], arr[j])) {
// Remove duplicate
arr[j] = null;
}
}
}
return arr.filter((el) => el !== null);
}
console.log(
removeDuplicates([
{ name: "ali", age: 15 },
{ al: "ali", pk: 15 },
{ ok: "ahmad", li: 13 },
{ name: "something", age: 24 },
{ name: "ali", age: 15 },
])
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment