Skip to content
Advertisement

Remove duplicates in array by checking if its the same as the next one

I am learning JavaScript right now and I want to practice for loops and if statements. So I found a little exercise: Remove all duplicates in the array. I know there a probably better solutions but I want to know why my code isn’t working. Can someone help me? Thx 🙂

var arr = [1, 1, 2, 3, 3, 3, 4, 5, 5];
var b = 0;

function arrRemover() {
    for (i = 0; i < arr.length; i++) {
        b++
        if (arr[b] == arr[b + 1]) {
            arr.splice[b + 1];
        }
    }
    return arr;
}

console.log(arrRemover());

Advertisement

Answer

splice is a method so you have to call that method with specific arguments.

You don’t need b here

Better not to loop over that array from start instead loop from backward so that you won’t skip over elements when you remove any element from an array beause if an elment gets deleted and you then counter increment and skip some elements

var arr = [1, 1, 2, 3, 3, 3, 4, 5, 5];

function arrRemover() {
    for (let i = arr.length - 1; i > 0; i--) {
        if (arr[i] === arr[i - 1]) {
            arr.splice(i, 1);
        }
    }
    return arr;
}

console.log(arrRemover());

You can also use Set here as:

var arr = [1, 1, 2, 3, 3, 3, 4, 5, 5];

function arrRemover() {
    return [...new Set(arr)];
}

console.log(arrRemover());
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement