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"
1array1 = array1.filter(function(val) {
2 return array2.indexOf(val) == -1;
3});
4// Or, with the availability of ES6:
5
6array1 = array1.filter(val => !array2.includes(val));
7
1uniqueArray = a.filter(function(item, pos) {
2 return a.indexOf(item) == pos;
3})
4
1function uniqByKeepFirst(a, key) {
2 let seen = new Set();
3 return a.filter(item => {
4 let k = key(item);
5 return seen.has(k) ? false : seen.add(k);
6 });
7}
8
9
10function uniqByKeepLast(a, key) {
11 return [
12 ...new Map(
13 a.map(x => [key(x), x])
14 ).values()
15 ]
16}
17
18//
19
20data = [
21 {a:1, u:1},
22 {a:2, u:2},
23 {a:3, u:3},
24 {a:4, u:1},
25 {a:5, u:2},
26 {a:6, u:3},
27];
28
29console.log(uniqByKeepFirst(data, it => it.u))
30console.log(uniqByKeepLast(data, it => it.u))