Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. function removeDuplicates(arr) {
  2.  
  3. const result = [];
  4. const duplicatesIndices = [];
  5.  
  6. // Loop through each item in the original array
  7. arr.forEach((current, index) => {
  8.  
  9. if (duplicatesIndices.includes(index)) return;
  10.  
  11. result.push(current);
  12.  
  13. // Loop through each other item on array after the current one
  14. for (let comparisonIndex = index + 1; comparisonIndex < arr.length; comparisonIndex++) {
  15.  
  16. const comparison = arr[comparisonIndex];
  17. const currentKeys = Object.keys(current);
  18. const comparisonKeys = Object.keys(comparison);
  19.  
  20. // Check number of keys in objects
  21. if (currentKeys.length !== comparisonKeys.length) continue;
  22.  
  23. // Check key names
  24. const currentKeysString = currentKeys.sort().join("").toLowerCase();
  25. const comparisonKeysString = comparisonKeys.sort().join("").toLowerCase();
  26. if (currentKeysString !== comparisonKeysString) continue;
  27.  
  28. // Check values
  29. let valuesEqual = true;
  30. for (let i = 0; i < currentKeys.length; i++) {
  31. const key = currentKeys[i];
  32. if ( current[key] !== comparison[key] ) {
  33. valuesEqual = false;
  34. break;
  35. }
  36. }
  37. if (valuesEqual) duplicatesIndices.push(comparisonIndex);
  38.  
  39. } // end for loop
  40.  
  41. }); // end arr.forEach()
  42.  
  43. return result;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement