2

how to find duplicates in an array and remove them using javascript?

3
  • What type variables will be in the array? Only strings? Commented Sep 13, 2010 at 10:52
  • sorry wasnt specific,i was thinking both string and integer arrays. Commented Sep 13, 2010 at 10:55
  • possible duplicate of unique() for arrays in javascript Commented Sep 13, 2010 at 11:16

3 Answers 3

3

To do this generically, you could use something like the following, which removes duplicates from the array in place. If you have an array that contains only strings or numbers, you could simplify this significantly.

var arrayContains = Array.prototype.indexOf ?
    function(arr, val) {
        return arr.indexOf(val) > -1;
    } :

    function(arr, val) {
        var i = arr.length;
        while (i--) {
            if (arr[i] === val) {
                return true;
            }
        }
        return false;
    }

function removeDuplicates(arr, equals) {
    var val, originalArr = arr.slice(0);
    arr.length = 0;

    for (var i = 0, len = originalArr.length; i < len; ++i) {
        val = originalArr[i];
        if (!arrayContains(arr, val)) {
            arr.push(val);
        }
    }

    return arr;
}

var arr = [1, 2, 2, 1, 3];
removeDuplicates(arr);
console.log(arr); // [1, 2, 3]
Sign up to request clarification or add additional context in comments.

Comments

1
var sampleArr=new Array(1,1,1,1,1,2,2,3,3,3,4,4,4); //Declare array
document.write(uniqueArr(sampleArr)); //Print the unique value

//Adds new uniqueArr values to temp array
function uniqueArr(a) {
 temp = new Array();
 for(i=0;i<a.length;i++){
  if(!contains(temp, a[i])){
   temp.length+=1;
   temp[temp.length-1]=a[i];
  }
 }
 return temp;
}

//Will check for the Uniqueness
function contains(a, e) {
 for(j=0;j<a.length;j++)if(a[j]==e)return true;
 return false;
}

Comments

0
for(var i=0; i < arr.length; i++)
{
    for(var j=i+1; j < arr.length; j++)
    {
        if(arr[j] == arr[i])
        {
            arr.splice(j, 1);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.