Given a ['0','1','1','2','3','3','3']
array, the result should be ['0','1','2','3']
.
To find a unique array and remove all the duplicates from the array in JavaScript, use the new Set() constructor and pass the array that will return the array with unique values. There are other approaches like: Using new ES6 feature: [… new Set( [1, 1, 2] )];
By using hashmap's key. In Java, the simplest way to get unique elements from the array is by putting all elements of the array into hashmap's key and then print the keySet(). The hashmap contains only unique keys, so it will automatically remove that duplicate element from the hashmap keySet.
Edited
ES6 solution:
[...new Set(a)];
Alternative:
Array.from(new Set(a));
Old response. O(n^2) (do not use it with large arrays!)
var arrayUnique = function(a) { return a.reduce(function(p, c) { if (p.indexOf(c) < 0) p.push(c); return p; }, []); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With