Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript remove all occurrence of duplicate element, leaving the only one that is unique

I want to remove elements that occurr more than once and get the unique element. The array always has 3 elements. Lets say i have an array [2,3,2], then I need to get 3 which is only unique in the array(removing both 2s, because they occur more than once).

I have tried with following code, but surely it doesnot work as expected.

var firstArrTemp = [2,3,2];
var sorted_arr = firstArrTemp.sort();
var unique_element;
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] != sorted_arr[i]) {
        unique_element=sorted_arr[i];
    }
}

alert(unique_element);

Thanks!

like image 853
WatsMyName Avatar asked Dec 04 '22 05:12

WatsMyName


2 Answers

This should do the trick:

Array.prototype.getUnique = function(){
    var uniques = [];
    for(var i = 0, l = this.length; i < l; ++i){
        if(this.lastIndexOf(this[i]) == this.indexOf(this[i])) {
            uniques.push(this[i]);
        }
    }
    return uniques;
}

// Usage:

var a = [2, 6, 7856, 24, 6, 24];
alert(JSON.stringify(a.getUnique()));

console.log(a.getUnique()); // [2, 7856]

To check if a specific item is unique in the array, it just checks if the first index it's found at, matches the last index it's found at.

like image 155
Cerbrus Avatar answered Dec 09 '22 15:12

Cerbrus


One alternative with filter() function:

var myArray = [1,2,3,2,2,4,3,7,3].sort();
var uniqueValues = myArray.filter(function(item, i, arr) {
  return (item !== arr[i-1] && item !== arr[i+1]);
});

Where uniqueValues = [1,4,7]

like image 29
Samuli Hakoniemi Avatar answered Dec 09 '22 15:12

Samuli Hakoniemi