DekGenius.com
JAVASCRIPT
how to find duplicates in an array
const numbers = [1, 2, 3, 2, 4, 5, 5, 6];
const set = new Set(numbers);
const duplicates = numbers.filter(item => {
if (set.has(item)) {
set.delete(item);
} else {
return item;
}
});
console.log(duplicates);
// [ 2, 5 ]
find duplicates in array
function findDuplicates(arr) {
const duplicates = new Set()
return arr.filter(item => {
if (duplicates.has(item)) {
return true
}
duplicates.add(item)
return false
})
}
find duplicate element on array
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 }
Find / Display duplicate numbers in array
var input = [1, 2, 5, 5, 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;
}, []);
console.log(duplicates);
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()
// => { 'age': 36, 'name': 'Bob' }
find array is duplicate or not
const numbers = [1, 2, 3, 2, 4, 5, 5, 6];
let isDuplicate = false;
// Outer for loop
for (let i = 0; i < numbers.length; i++) {
// Inner for loop
for (let j = 0; j < numbers.length; j++) {
// Skip self comparison
if (i !== j) {
// Check for duplicate
if (numbers[i] === numbers[j]) {
isDuplicate = true;
// Terminate inner loop
break;
}
}
// Terminate outer loop
if (isDuplicate) {
break;
}
}
}
if (!isDuplicate) {
console.log(`Array doesn't contain duplicates.`);
} else {
console.log(`Array contains duplicates.`);
}
// Output: Array contains duplicates.
duplicate array values
public class Main {
public static void main(String[] args) {
int[] arr1 = {1,2,3,3,4};
for (int i = 0; i < arr1.length-1 ; i++) {
for (int j = 0; j < arr1.length; j++) {
if (arr1[i]==arr1[j] && (j != i)){
System.out.println("array's duplicate number: " +
arr1[j]);
}
}
}
}
}
array iteration + find duplicates
function lonelyinteger(a: number[]): number {
for (let item of a) {
const items = a.filter(el => item === el)
if (items.length === 1) {
return item
}
}
}
const a:number[] = [1,2,3,4,3,2,1]
const result:number = lonelyinteger(a);
console.log(result)
© 2022 Copyright:
DekGenius.com