-4

I have the an array which have some values but i need not want the same value in my array

Example:

var myarray=new Array();
myarray[0]="Apple",
myarray[1]="Grapes",
myarray[2]="Apple",

i want my array should contain only grapes and apple.

sdespont
  • 13,915
  • 9
  • 56
  • 97
K.P
  • 66
  • 7

3 Answers3

2

Here i found some method. Source: Removing duplicate element in an array

function eliminateDuplicates(arr) {
 var i,
 len=arr.length,
 out=[],
 obj={};

 for (i=0;i<len;i++) {
   obj[arr[i]]=0;
 }

 for (i in obj) {
   out.push(i);
 }

 return out;
}
Community
  • 1
  • 1
Hary
  • 5,690
  • 7
  • 42
  • 79
2

This function will remove duplicate values from an array (it keeps the last one):

function removeDups(arr) {
    var temp = {}, val;
    for (var i = arr.length - 1; i >= 0; i--) {
        val = arr[i];
        if (temp[val] === true) {
            // already have one of these so remove this one
            arr.splice(i, 1);
        } else {
             temp[val] = true;
        }
    }
}

If you want to keep the first one instead of the last one, you can use this version:

function removeDups(arr) {
    var temp = {}, val;
    for (var i = 0; i < arr.length; i++) {
        val = arr[i];
        if (temp[val] === true) {
            // already have one of these so remove this one
            arr.splice(i, 1);
            // correct our for loop index to account for removing the current item
            --i;
        } else {
             temp[val] = true;
        }
    }
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0
unique = myArray.filter(function(elem, pos) {
    return myArray.indexOf(elem) == pos;
})

unique will have only unique values.

Note: The above relies on filter, which is new as of ECMAScript5 and not present in legacy browsers (including IE8), but present in all modern ones. If you have to support legacy browsers, use an ES5 shim (as filter is shim-able). Also note that indexOf may not be present in really old browsers like IE7.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Engineer
  • 5,911
  • 4
  • 31
  • 58
  • 1
    Please don't post jQuery-specific answers to non-jQuery questions. – T.J. Crowder Jan 28 '13 at 06:33
  • I recommend **always** warning the OP when you rely on ES5 features (yes, even in 2013). I took the liberty of doing it for you (not least because an SO bug wouldn't let me remove the downvote after your edit). – T.J. Crowder Jan 28 '13 at 06:43