Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. /**
  2. * Primitives
  3. */
  4.  
  5. // If an Array only contains primitive values, we can deduplicate it by only using the filter and indexOf methods.
  6. var deduped = [ 1, 1, 'a', 'a' ].filter(function (el, i, arr) {
  7. return arr.indexOf(el) === i;
  8. });
  9. console.log(deduped); // [ 1, 'a' ]
  10.  
  11. // The ES6 (ECMAScript 2015) version
  12. // We can write this in a more compact way using an arrow function.
  13. var deduped = [ 1, 1, 'a', 'a' ].filter( (el, i, arr) => arr.indexOf(el) === i);
  14. console.log(deduped); // [ 1, 'a' ]
  15.  
  16. // But with the introduction of Sets and the from method, we can achieve the same result in a more concise way.
  17. var deduped = Array.from( new Set([ 1, 1, 'a', 'a' ]) );
  18. console.log(deduped); // [ 1, 'a' ]
  19.  
  20. /**
  21. * Objects
  22. */
  23.  
  24. // We can't use the same approach when the elements are Objects,
  25. // because Objects are stored by reference and primitives are stored by value.
  26. 1 === 1 // true
  27. 'a' === 'a' // true
  28. { a: 1 } === { a: 1 } // false
  29.  
  30. // Therefore we need to change our approach and use a hash table.
  31.  
  32. function dedup(arr) {
  33. var hashTable = {};
  34.  
  35. return arr.filter(function (el) {
  36. var key = JSON.stringify(el);
  37. var match = Boolean(hashTable[key]);
  38.  
  39. return (match ? false : hashTable[key] = true);
  40. });
  41. }
  42.  
  43. var deduped = dedup([
  44. { a: 1 },
  45. { a: 1 },
  46. [ 1, 2 ],
  47. [ 1, 2 ]
  48. ]);
  49.  
  50. console.log(deduped); // [ {a: 1}, [1, 2] ]
  51.  
  52. // Because a hash table in javascript is simply an Object, the keys will always be of the type String.
  53. // This means that normally we can't distinguish between strings and numbers of the same value, i.e. 1 and '1'.
  54.  
  55. var hashTable = {};
  56.  
  57. hashTable[1] = true;
  58. hashTable['1'] = true;
  59.  
  60. console.log(hashTable); // { '1': true }
  61.  
  62. // However, because we're using JSON.stringify, keys that are of the type String,
  63. // will be stored as an escaped string value, giving us unique keys in our hashTable.
  64.  
  65. var hashTable = {};
  66.  
  67. hashTable[JSON.stringify(1)] = true;
  68. hashTable[JSON.stringify('1')] = true;
  69.  
  70. console.log(hashTable); // { '1': true, '\'1\'': true }
  71.  
  72. // This means duplicate elements of the same value, but of a different type,
  73. // will still be deduplicated using the same implementation.
  74.  
  75. var deduped = dedup([
  76. { a: 1 },
  77. { a: 1 },
  78. [ 1, 2 ],
  79. [ 1, 2 ],
  80. 1,
  81. 1,
  82. '1',
  83. '1'
  84. ]);
  85.  
  86. console.log(deduped); // [ {a: 1}, [1, 2], 1, '1' ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement