1let strArray = [ "q", "w", "w", "w", "e", "i", "u", "r"];
2let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index)
3
4console.log(findDuplicates(strArray)) // All duplicates
5console.log([...new Set(findDuplicates(strArray))]) // Unique duplicates
1var array = [1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 7, 8, 5, 22, 1, 2, 511, 12, 50, 22];
2
3console.log([...new Set(
4 array.filter((value, index, self) => self.indexOf(value) !== index))]
5);
1// JavaScript - finds if there is duplicate in an array.
2// Returns True or False.
3
4const isThereADuplicate = function(arrayOfNumbers) {
5 // Create an empty associative array or hash.
6 // This is preferred,
7 let counts = {};
8 // // but this also works. Comment in below and comment out above if you want to try.
9 // let counts = [];
10
11 for(var i = 0; i <= arrayOfNumbers.length; i++) {
12 // As the arrayOfNumbers is being iterated through,
13 // the counts hash is being populated.
14 // Each value in the array becomes a key in the hash.
15 // The value assignment of 1, is there to complete the hash structure.
16 // Once the key exists, meaning there is a duplicate, return true.
17 // If there are no duplicates, the if block completes and returns false.
18 if(counts[arrayOfNumbers[i]] === undefined) {
19 counts[arrayOfNumbers[i]] = 1;
20 } else {
21 return true;
22 }
23 }
24 return false;
25}
1var input = [1, 2, 3, 1, 3, 1];
2
3var duplicates = input.reduce(function(acc, el, i, arr) {
4 if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
5}, []);
6
7document.write(duplicates); // = 1,3 (actual array == [1, 3])
1function findUniq(arr) {
2 return arr.find(n => arr.indexOf(n) === arr.lastIndexOf(n));
3}
4
5console.log(findUniq([ 0, 1, 0 ]))
6console.log(findUniq([ 1, 1, 1, 2, 1, 1 ]))
7console.log(findUniq([ 3, 10, 3, 3, 3 ]))
8console.log(findUniq([ 7, 7, 7, 20, 7, 7, 7 ]))
1var names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']
2
3var uniq = names
4 .map((name) => {
5 return {
6 count: 1,
7 name: name
8 }
9 })
10 .reduce((a, b) => {
11 a[b.name] = (a[b.name] || 0) + b.count
12 return a
13 }, {})
14
15var duplicates = Object.keys(uniq).filter((a) => uniq[a] > 1)
16
17console.log(duplicates) // [ 'Nancy' ]