Click here to Skip to main content
15,616,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was trying to retrieve the duplicate array items using the for a loop. The loop was successful in giving the duplicates but it is giving multiple instances of the duplicates separately ?? How to get single instances of the duplicate array elements in a single new array ??

  let arr = ['A', 'B', 'A', 'C', 'B'];
    let result = false;
    // iterate over the array
    for (let i = 0; i < arr.length; i++) {
        // compare the first and last index of an element
        let uniqueChars = [];
        if (arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])) {


// Actual output 

// Desired output 
['A', 'B']

What I have tried:

Used for loop with the condition to detect duplicate elements. Initiated an empty array with the name uniqueChars.The addition of duplicate elements is taking place with multiple instances. How to get a single instance of duplicate elements in a single array ??
Updated 16-Mar-22 23:06pm

I would try
if (arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])) {
// or
if (i !== arr.lastIndexOf(arr[i])) {

This way, array item shows only iit is not the last one.
Share this answer
Apoorv 2021 16-Mar-22 19:31pm    
indexOf is important for checking the condition for the duplicacy of items
Patrice T 16-Mar-22 19:44pm    
My bad, done a correction.
Patrice T 16-Mar-22 19:45pm    
I don't say it is not important, I say use it only once.
Apoorv 2021 17-Mar-22 1:53am    
i have used only once..the other is last index of
Patrice T 17-Mar-22 4:23am    
Did you tried my change ?
Do you get correct result ?
const arr = ['A', 'B', 'A', 'C', 'B'];
const duplicateChars = arr.filter((char, index) => arr.indexOf(char) < index);
Array.prototype.filter() - JavaScript | MDN[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900