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)}`);
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, 9, 4, 5, 7];
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);
javascript how to check the indexes of duplicates elements in an array
// 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);
}
}
const order = ["apple", "banana", "orange", "banana", "apple", "banana"];
const result = order.reduce(function (prevVal, item) {
if (!prevVal[item]) {
// if an object doesn't have a key yet, it means it wasn't repeated before
prevVal[item] = 1;
} else {
// increase the number of repetitions by 1
prevVal[item] += 1;
}
// and return the changed object
return prevVal;
}, {}); // The initial value is an empty object.
console.log(result); // { apple: 2, banana: 3, orange: 1 }
how to get duplicate values from array in javascript
let a = [1, 2, 3, 4, 2, 2, 4, 1, 5, 6]
let b = [...new Set(a.sort().filter((o, i) => o !== undefined && a[i + 1] !== undefined && o === a[i + 1]))]
// b is now [1, 2, 4]
javascript find duplicates in array using for loop
var inputs = [4, 2, 5, 2, 3, 4, 4, 5, 6, 7, 1, 3, 6, 8];
var duplicates = [];
var result = 0;
for (var i = 0; i < inputs.length; i++) {
for (var c = 0; c < inputs.length; c++) {
if (inputs[i] == inputs[c]) {
result = result + 1;
if (result == 2) {
if (duplicates.indexOf(inputs[c]) !== -1) {
} else {
duplicates.push(inputs[c]);
}
}
}
}
result = 0;
}
console.log(duplicates.sort());