find duplicate item in array javascript code example
Example 1: javascript find duplicate in array
const isThereADuplicate = function(arrayOfNumbers) {
let counts = {};
for(var i = 0; i <= arrayOfNumbers.length; i++) {
if(counts[arrayOfNumbers[i]] === undefined) {
counts[arrayOfNumbers[i]] = 1;
} else {
return true;
}
}
return false;
}
Example 2: 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 3: how to get duplicate values from array in javascript
var input = [1, 2, 3, 1, 3, 1];
var duplicates = input.reduce(function(acc, el, i, arr) {
if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
}, []);
document.write(duplicates);
Example 4: how to get duplicate values from array in javascript
const arr = ["q", "w", "w", "e", "i", "u", "r"]
arr.reduce((acc, cur) => {
if(acc[cur]) {
acc.duplicates.push(cur)
} else {
acc[cur] = true
}
}, { duplicates: [] })