Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting both values from array if duplicate - JavaScript/jQuery

I have an array here:

var myArr = [1, 1, 2, 5, 5, 7, 8, 9, 9];

Now I want to remove both appearances of a duplicate. So the desired result is not:

var myArr = [1, 2, 5, 7, 8 ,9];

but

var myArr = [2, 7, 8];

Basically I know how to remove duplicates, but not in that that special way. Thats why any help would be really appreciated!

Please note: My array is filled with strings. The numbers here were only used as an example.

like image 835
Sven Avatar asked Jul 13 '12 16:07

Sven


1 Answers

Wherever removing duplicates is involved, it's not a bad idea to use a set data structure.

JavaScript doesn't have a native set implementation, but the keys of an object work just as well - and in this case help because then the values can be used to keep track of how often an item appeared in the array:

function removeDuplicates(arr) {
    var counts = arr.reduce(function(counts, item) {
        counts[item] = (counts[item]||0)+1;
        return counts;
    }, {});
    return Object.keys(counts).reduce(function(arr, item) {
        if(counts[item] === 1) {
            arr.push(item);
        }
        return arr;
    }, []);
}

var myArr = [1, 1, 2, 5, 5, 7, 8, 9, 9];
removeDuplicates(myArr);

Check out the example on jsfiddle.

Alternately, you could not use calls to reduce(), and instead use for and for(item in counts) loops:

function removeDuplicates(arr) {
    var counts = {};
    for(var i=0; i<arr.length; i++) {
        var item = arr[i];
        counts[item] = (counts[item]||0)+1;
    }
    var arr = [];
    for(item in counts) {
        if(counts[item] === 1) {
            arr.push(item);
        }
    }
    return arr;
}

Check out the example on jsfiddle.

like image 64
Richard JP Le Guen Avatar answered Oct 22 '22 18:10

Richard JP Le Guen