how to check an array for duplicates code example
Example 1: count duplicates array js
uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);
Example 2: java find duplicates in array
package dto;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class DuplicatesInArray{
public static void main(String args[]) {
String[] names = { "Java", "JavaScript", "Python", "C", "Ruby", "Java" };
System.out.println("Finding duplicate elements in array using brute force method");
for (int i = 0; i < names.length; i++) {
for (int j = i + 1; j < names.length; j++) {
if (names[i].equals(names[j]) ) {
}
}
}
System.out.println("Duplicate elements from array using HashSet data structure");
Set<String> store = new HashSet<>();
for (String name : names) {
if (store.add(name) == false) {
System.out.println("found a duplicate element in array : "
+ name);
}
}
System.out.println("Duplicate elements from array using hash table");
Map<String, Integer> nameAndCount = new HashMap<>();
for (String name : names) {
Integer count = nameAndCount.get(name);
if (count == null) {
nameAndCount.put(name, 1);
} else {
nameAndCount.put(name, ++count);
}
}
Set<Entry<String, Integer>> entrySet = nameAndCount.entrySet();
for (Entry<String, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
System.out.println("Duplicate element from array : "
+ entry.getKey());
}
}
}
}
Output :
Finding duplicate elements in array using brute force method
Duplicate elements from array using HashSet data structure
found a duplicate element in array : Java
Duplicate elements from array using hash table
Duplicate element from array : Java
Example 3: javascript check if array has duplicates
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
Example 4: find-array-duplicates
npm i find-array-duplicates
import duplicates from 'find-array-duplicates'
const names = [
{ 'age': 36, 'name': 'Bob' },
{ 'age': 40, 'name': 'Harry' },
{ 'age': 1, 'name': 'Bob' }
]
duplicates(names, 'name').single()
Example 5: java find duplicates in array
for (String name : names)
{
if (set.add(name) == false)
{
}
}