How can I remove the duplicate element from an array?

Viewed 44

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.

1 Answers

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);
}
Related