xxxxxxxxxx
function hasDuplicates(array) {
// create a set to store unique values
const uniqueValues = new Set();
// loop through the array
for (let i = 0; i < array.length; i++) {
// if the value is not in the set, add it
if (!uniqueValues.has(array[i])) {
uniqueValues.add(array[i]);
} else {
// if the value is already in the set, return true
return true;
}
}
// if the loop completes and there are no duplicates, return false
return false;
}
const numbers = [1, 2, 3, 4, 5];
const hasDuplicates = hasDuplicates(numbers); // returns false
const letters = ['a', 'b', 'c', 'b'];
const hasDuplicates = hasDuplicates(letters); // returns true
xxxxxxxxxx
const allEqual = arr => arr.every(v => v === arr[0]);
allEqual([1,1,1,1]); // true
xxxxxxxxxx
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
xxxxxxxxxx
let arr = [1, 2, 3, 4, 5, 5];
const seen = new Set();
const duplicates = arr.filter(n => seen.size === seen.add(n).size);
console.log(duplicates); // [ 5 ]
console.log(duplicates.length); // 1
xxxxxxxxxx
function findDuplicates(arr) {
let seen = {};
let duplicates = [];
for (let i = 0; i < arr.length; i++) {
if (seen[arr[i]]) {
duplicates.push(arr[i]);
} else {
seen[arr[i]] = true;
}
}
return duplicates;
}
xxxxxxxxxx
const arr = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"]
const counts = {};
arr.forEach((x) => {
counts[x] = (counts[x] || 0) + 1;
});
console.log(counts)
xxxxxxxxxx
const findDuplicates = (arr) => {
let sorted_arr = arr.slice().sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
// (we use slice to clone the array so the
// original array won't be modified)
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)}`);
xxxxxxxxxx
[1, 2, 3].every((e, i, a) => a.indexOf(e) === i) // true
[1, 2, 1].every((e, i, a) => a.indexOf(e) === i) // false
xxxxxxxxxx
// A method to find a duplicate value in an array and the index of the duplicates
// array can be any data type
const arry = ["1", "2", "3", "1"];
let set = new Set();
for (let i = 0; i < arry.length; i++) {
let pastSize = set.size;
set.add(arry[i]);
let newSize = set.size;
if (pastSize == newSize) {
console.log("The array has duplicates at index: ", i);
}
}
xxxxxxxxxx
function checkIfDuplicateExists(w){
return new Set(w).size !== w.length
}
console.log(
checkIfDuplicateExists(["a", "b", "c", "a"])
// true
);
console.log(
checkIfDuplicateExists(["a", "b", "c"]))
//false