3

Possible Duplicate:
Remove duplicates from an array of objects in javascript

I'm trying to remove any duplicates in an array. For example if I have 112233 I want to return only 123.

My code:

function array_unique(array) {
    var array_length = array.length;
    var new_array = [];
    for (var i = 0; i < array_length; i++) {
        if (array[i] == array[i + 1]) {

        }
        new_array.push(array[i]);
    }
    return new_array;
}

I don't know what to type in the if so I can remove the doubles

Community
  • 1
  • 1
user1915308
  • 354
  • 4
  • 12

5 Answers5

3

Here you can remove the duplicates with complexity O(n).

var elems = {},
    arr = [1,2,1,1,2,3,3,3,3,4];
arr = arr.filter(function (e) {
    if (elems[e] === undefined) {
        elems[e] = true;
        return true;
    }
    return false;
});

I use the elems hash (object) to remember all already existing elements. If the current element is a key in the elems hash I just filter it.

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
2

Use prototype for Array like this

Array.prototype.removeDups = function(){
            var local_array = this;
            return local_array.filter(function(elem, pos) {
                return local_array.indexOf(elem) == pos;
            });
        }
Ranganadh Paramkusam
  • 4,258
  • 2
  • 22
  • 33
1
arrayWithNoDuplicates = new_array.filter(function(element, position) {
    return myArray.indexOf(element) == position;
})
Moseleyi
  • 2,585
  • 1
  • 24
  • 46
0
  fxnUniqOptns = function (array) {
    var oOptns = [];
    $.each(array, function (i, val) {
        if ($.inArray(val, oOptns) == -1)
            oOptns.push(val);
    });
    oOptns = oOptns.sort();
    return oOptns;
}
Gadde
  • 1,451
  • 15
  • 37
0

give array.splice(i, 1) after the if condition,this will remove the current element,so that duplicates will be removed.

MahaSwetha
  • 1,058
  • 1
  • 12
  • 21