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);
1function findDuplicates(arr) {
2 const duplicates = new Set()
3
4 return arr.filter(item => {
5 if (duplicates.has(item)) {
6 return true
7 }
8 duplicates.add(item)
9 return false
10 })
11}
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}
1const findDuplicates = (arr) => {
2 let sorted_arr = arr.slice().sort(); // You can define the comparing function here.
3 // JS by default uses a crappy string compare.
4 // (we use slice to clone the array so the
5 // original array won't be modified)
6 let results = [];
7 for (let i = 0; i < sorted_arr.length - 1; i++) {
8 if (sorted_arr[i + 1] == sorted_arr[i]) {
9 results.push(sorted_arr[i]);
10 }
11 }
12 return results;
13}
14
15let duplicatedArray = [9, 4, 111, 2, 3, 4, 9, 5, 7];
16console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);
1const findDuplicates = (arr) => {
2 let sorted_arr = arr.slice().sort(); // You can define the comparing function here.
3 // JS by default uses a crappy string compare.
4 // (we use slice to clone the array so the
5 // original array won't be modified)
6 let results = [];
7 for (let i = 0; i < sorted_arr.length - 1; i++) {
8 if (sorted_arr[i + 1] == sorted_arr[i]) {
9 results.push(sorted_arr[i]);
10 }
11 }
12 return results;
13}
14
15let duplicatedArray = [9, 4, 111, 2, 3, 9, 4, 5, 7];
16console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);