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.
JavaScript
x
11
11
1
var firstArrTemp = [2,3,2];
2
var sorted_arr = firstArrTemp.sort();
3
var unique_element;
4
for (var i = 0; i < sorted_arr.length - 1; i++) {
5
if (sorted_arr[i + 1] != sorted_arr[i]) {
6
unique_element=sorted_arr[i];
7
}
8
}
9
10
alert(unique_element);
11
Thanks!
Advertisement
Answer
This should do the trick:
JavaScript
1
16
16
1
Array.prototype.getUnique = function(){
2
var uniques = [];
3
for(var i = 0, l = this.length; i < l; ++i){
4
if(this.lastIndexOf(this[i]) == this.indexOf(this[i])) {
5
uniques.push(this[i]);
6
}
7
}
8
return uniques;
9
}
10
11
// Usage:
12
13
var a = [2, 6, 7856, 24, 6, 24];
14
alert(JSON.stringify(a.getUnique()));
15
16
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.