Click here to Skip to main content
15,886,199 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'];
    console.log(arr.lastIndexOf("A"))
    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])) {
            uniqueChars.push(arr[i]);

            console.log(uniqueChars)
        }
    }

// Actual output 
['A']'['B']['A']['B']

// 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 ??
Posted
Updated 16-Mar-22 23:06pm

I would try
JavaScript
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
 
v3
Comments
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 ?
Try:
JavaScript
const arr = ['A', 'B', 'A', 'C', 'B'];
const duplicateChars = arr.filter((char, index) => arr.indexOf(char) < index);
console.log(duplicateChars);
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