how to check duplicate elements in array code example
Example 1: find duplicate values in array javascript
const findDuplicates = (arr) => {
let sorted_arr = arr.slice().sort();
let results = [];
for (let i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
let duplicatedArray = [9, 4, 111, 2, 3, 4, 9, 5, 7];
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);
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: check for duplicates in array javascript
[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i)