Chuck Reynolds
Chuck Reynolds

Reputation: 45

Remove all items that have duplicates in array Javascript

I have searched on here and have not found a solution. Obviously I will be corrected if I am wrong. What I am trying to do is return values that do not have a duplicates in an array.

Examples:

myArr = [2,1,2,3] // answer [1,3]

myArr = [3,1,2,2,3] // answer [1]

I would post some code but I have not been able to figure this out myself and the only code examples I have found are for removing any duplicate values.

The possible solution above is to return no duplicates... I am trying to return values that are don't have duplicates.

Upvotes: 0

Views: 167

Answers (4)

Harsha pps
Harsha pps

Reputation: 2218

var yourArray = [1, 2, 1, 3];

        var uniqueValues = [];
        $.each(yourArray, function (i, value) { //taking each 'value' from yourArray[]
            if ($.inArray(value, uniqueValues) === -1) { 
                 uniqueValues.push(value); // Pushing the non - duplicate value into the uniqueValues[] 
            }
        });            
        console.log(uniqueValues);

Result: [1,2,3];

Upvotes: 0

xpeiro
xpeiro

Reputation: 760

If is not an associative array (your case):

var myArr = [1,2,2,3,4,4,1,5];
var myNewArr = [];

if (myArr.length > 0 )
{
    myNewArr[0] = myArr[myArr.length-1];    
}

var count = 1;

myArr.sort();

for (var i = myArr.length - 2; i >= 0; i--) {

    if(myArr[i] != myArr[i-1])
    {
        myNewArr[count] = myArr[i];
        count++;
    }
}

Upvotes: 0

code_monk
code_monk

Reputation: 10148

var isUnique = function(v,i,arr){
   // return true if the first occurrence is the last occurrence 
   return ( arr.indexOf(v) === arr.lastIndexOf(v) ); 
};

var uniqueVals = myArr.filter(isUnique);

console.log( uniqueVals );

Upvotes: 2

Hamms
Hamms

Reputation: 5107

One option is to use the optional second argument to indexOf to find duplicate indexes. Consider that for a given element e and an index i:

  1. if e is the first of two identical elements in the array, indexOf(e) will return i and indexOf(e, i + 1) will return the index of the second element.
  2. if e is the second of two identical elements in the array, indexOf(e) will return the index of the first element, and indexOf(e, i + 1) will return -1
  3. if e is a unique element, indexOf(e) will return i and indexOf(e, i + 1) will return -1.

Therefore:

myArr.filter(function (e, i, a) {
  return a.indexOf(e) === i && a.indexOf(e, i + 1) === -1
});

Upvotes: 4

Related Questions