brndng
brndng

Reputation: 103

Return unique element that does not have duplicates in an array

I am trying to return an array with only unique elements that do not have duplicates within the array in no particular order.

[1,2,3,3,3,4,4,2] would return 1

["hello", "truck", 2, "truck", 2, "truck"] would return "hello"

So far I have only been able to return unique elements using the filter() function, but I am not sure where to go.

Basically if there are duplicates I want both values removed from the array.

This sounds simple enough, but I am having a serious mental hiccup.

Below is my code:

function diff(arr1, arr2) {
  var newArr = [];

   newArr = arr1.concat(arr2);

   newArr = newArr.filter(function(elem, index, self) {
        return index == self.indexOf(elem);
    });

    console.log(newArr);
    return newArr;

}

diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);
//should return 4

Upvotes: 5

Views: 1914

Answers (3)

void
void

Reputation: 36703

Compare the indexOf and lastIndexOf, if they are equal then the element has no duplicates. Use .filter with this logic.

function diff(arr1, arr2) {
  return arr1.concat(arr2).filter(function(elem, index, self) {
    return self.indexOf(elem)==self.lastIndexOf(elem);
  });
}

alert(diff([1, 2, 3, 5], [1, 2, 3, 4, 5]));

Upvotes: 6

Idos
Idos

Reputation: 15310

To get only the unique items in your array you may use the filter method like so:

function unique(val, index, self) { 
    return index === self.indexOf(val);
}

You can use it like so:

var arr = ['1','2','3','3'];
var uniqueArr = arr.filter(unique); // will return ['1', '2', '3']

This will works without jQuery or prototype.js & for arrays with values of mixed types.

Upvotes: -2

Aaron Gates
Aaron Gates

Reputation: 469

You could do something like this:

function findUniques(arr) {
    var i = 0;
    while(i !== arr.length) {
        if(arr.slice(i+1,arr.length-1).indexOf(arr[i]) > -1) {
            arr = arr.splice(i,0);
        } else {
            i++;
        }
    }
}

This would leave the unique items in the array in reverse order of how they were found. To avoid that, you iterate from the end of the array and let i decrease to zero, if you care about the order.

Upvotes: 1

Related Questions