Jorrex
Jorrex

Reputation: 1500

removing double values from array, not just the duplicate in javascript

So I have an array with 7 values:

var names = ["Tom", "James", "Matthew", "Jordy", "Jeremy", "Jasper", "Jordy"]

I need to get rid of both "Jordy", not just one, but both of them.

I'm using plain JS and a bit of jQuery. I know I can filter out one of them, but I don't know how to do both.

the result would have to be:

var names = ["Tom", "James", "Matthew", "Jeremy", "Jasper"]

Upvotes: 2

Views: 135

Answers (2)

garethdn
garethdn

Reputation: 12373

What you need to do here is avail of both indexOf and lastIndexOf. The other solution will only work if you already know the name of the duplicates that you wish to remove.

names = names.filter(function(item) {
    return names.indexOf(item) === names.lastIndexOf(item);
});

Here we check to see if the position of the first occurrence of the item in the array is equal to the position of the last occurrence of the item in the array. If so, we know the item is not a duplicate. If this predicate fails we know that the item appears more than once in the array and we don't return it.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707696

If you are OK with the results being returned in a new array, then .filter() is pretty easy:

var names = ["Tom", "James", "Matthew", "Jordy", "Jeremy", "Jasper", "Jordy"];
names = names.filter(function(item) {
    return item !== "Jordy";
});

If you want to modify the current array, you can use .splice() with a backwards traverse.

var names = ["Tom", "James", "Matthew", "Jordy", "Jeremy", "Jasper", "Jordy"];
for (var i = names.length - 1; i >= 0; i--) {
    if (names[i] === "Jordy") {
        names.splice(i, 1);
    }
}

Upvotes: 1

Related Questions