1const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
2
3let unique = [...new Set(names)];
4console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
1// 1. filter()
2function removeDuplicates(array) {
3 return array.filter((a, b) => array.indexOf(a) === b)
4};
5// 2. forEach()
6function removeDuplicates(array) {
7 let x = {};
8 array.forEach(function(i) {
9 if(!x[i]) {
10 x[i] = true
11 }
12 })
13 return Object.keys(x)
14};
15// 3. Set
16function removeDuplicates(array) {
17 array.splice(0, array.length, ...(new Set(array)))
18};
19// 4. map()
20function removeDuplicates(array) {
21 let a = []
22 array.map(x =>
23 if(!a.includes(x) {
24 a.push(x)
25 })
26 return a
27};
28/THIS SITE/ "https://dev.to/mshin1995/back-to-basics-removing-duplicates-from-an-array-55he#comments"
1const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
2
3function removeDups(names) {
4 let unique = {};
5 names.forEach(function(i) {
6 if(!unique[i]) {
7 unique[i] = true;
8 }
9 });
10 return Object.keys(unique);
11}
12
13removeDups(names); // // 'John', 'Paul', 'George', 'Ringo'
1const numbers = [1 , 21, 21, 34 ,12 ,34 ,12];
2const removeRepeatNumbers = array => [... new Set(array)]
3removeRepeatNumbers(numbers) // [ 1, 21, 34, 12 ]
1//ES6
2let uniqueArray = [...new Set(arrayWithDuplicates)];
3
4//Alternative
5function removeArrayDuplicates(arrayWithDuplicates) {
6 let seen = {};
7 let uniqueArray = [];
8 let len = arrayWithDuplicates.length;
9 let j = 0;
10 for(let i = 0; i < len; i++) {
11 let item = arrayWithDuplicates[i];
12 if(seen[item] !== 1) {
13 seen[item] = 1;
14 uniqueArray[j++] = item;
15 }
16 }
17 return uniqueArray;
18}