Example 1: java array check duplicates
duplicates = false;
for(i = 0; i < zipcodeList.length; i++) {
for(j = i + 1; k < zipcodeList.length; j++) {
if(j != i && zipcodeList[j] == zipcodeList[i]) {
duplicates = true;
}
}
}
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: js find duplicates in array
const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']
const count = names =>
names.reduce((a, b) => ({ ...a,
[b]: (a[b] || 0) + 1
}), {})
const duplicates = dict =>
Object.keys(dict).filter((a) => dict[a] > 1)
console.log(count(names))
console.log(duplicates(count(names)))
Example 4: javascript check if array has duplicates
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
Example 5: javascript get duplicates in array
function getDuplicateArrayElements(arr){
var sorted_arr = arr.slice().sort();
var results = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] === sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
var colors = ["red","orange","blue","green","red","blue"];
var duplicateColors= getDuplicateArrayElements(colors);
Example 6: 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()