0

I'm trying to iterate through the entire array, and if a duplicate is found it should be removed for which I'm using splice.

a = [1, 2, 3, 4, 3];

for (i = 0; i < a.length; i++) {
  for (j = i + 1; j < a.length; j++) {
    if (a[i] == a[j]) {
      a.splice(a[i], 1);
      i--;
    }
  }
}

console.log(a);

Expected Output is : [1,2,4,3]

Your help/advice will be highly appreciated. Thanks in advance.

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 2
    Does this answer your question? [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) or [Remove duplicate values from JS array](https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array) – WOUNDEDStevenJones Sep 09 '22 at 16:10
  • 3
    `splice(a[i]` <-- you are using the index value, not the index where you found it! – epascarello Sep 09 '22 at 16:10

1 Answers1

-1

try this : The splice method allows the index instead of the element.

try {
    let a = [1, 2, 3, 4, 3];
    console.log('before', a);
    for (let i = 0; i < a.length; i++) {
        for (let j = i + 1; j < a.length; j++) {
            if (a[i] == a[j]) {
                a.splice(i, 1);
                i--
            }
        }
    }
    console.log('after', a);
} catch (error) {
    console.log(error);
}
Md Joynul Abedin
  • 164
  • 1
  • 11