Below is an example array:
const attD = [1, 2, 3, 4, 3, 3]
How can we get the index of the duplicate values from this array? In this example, 3 is repeated thrice. So, I want to get the index 4, index 5 as these are duplicated at that positions (ignoring the first occurrence).
I have tried the below code, but it is giving me values. Instead, I need the index.
const findDuplicates = attD => attD.filter((item, index) => attD.indexOf(item) !== index);
const duplicates = findDuplicates(attD);
console.log(duplicates);
CodePudding user response:
- With
.map(), add the index of duplicated values into the array. For non-duplicate value, will be added withundefinedvalue [Will be filtered in Step 2]. - With
.filter(), remove the value which isundefinedfrom the array.
const attD = [1, 2, 3, 4, 3, 3];
const findDuplicates = attD => attD.map((item, index) => {
if (attD.indexOf(item) !== index)
return index;
}).filter(x => x); // Equivalent to .filter(x => x != undefined || x != null)
const duplicates = findDuplicates(attD);
console.log(duplicates);
CodePudding user response:
You can use this solution:
const attD = [1, 2, 3, 4, 3, 3]
const findDuplicates = attD => attD.map((item, index) => {
if (attD.indexOf(item) !== index)
return index;
}).filter(Boolean);
and you can use set:
const attD = [1, 2, 3, 4, 3, 3];
const setAttd = new Set(attD);
const findDuplicates = attD => attD.map((item, index) => {
if (setAttd.has(item)) {
setAttd.delete(item);
} else {
return index;
}
}).filter(Boolean);
