-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.

6
  • 2
    it does contain Apples and Grapes only - in your example? Commented Jan 28, 2013 at 6:30
  • stackoverflow.com/questions/840781/… Commented Jan 28, 2013 at 6:30
  • No i have just for the example value may differ. Commented Jan 28, 2013 at 6:31
  • @K.P: Why wouldn't you quote an example that actually fit the problem statement?! Commented Jan 28, 2013 at 6:32
  • 2
    ok, is it that you a) want to remove duplicates or b) want to remove specific values? Commented Jan 28, 2013 at 6:32

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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;
        }
    }
}

Comments

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.

2 Comments

Please don't post jQuery-specific answers to non-jQuery questions.
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.