javascript tutorial - [Solved-5 Solutions] Unique values in an array - javascript - java script - javascript array



Problem:

We have an array of numbers that we need to make sure are unique. We found the code snippet below on the internet and it works great until the array has a zero in it. We found this other script here on SO that looks almost exactly like it, but it doesn't fail. So for the sake of helping me learn, can someone help me determine where the prototype script is going wrong ?

Array.prototype.getUnique = function() {
 var o = {}, a = [], i, e;
 for (we = 0; e = this[i]; i++) {o[e] = 1};
 for (e in o) {a.push (e)};
 return a;
}
click below button to copy the code. By JavaScript tutorial team

Solution 1:

With JavaScript 1.6 / ECMAScript 5 we can use the native filter method of an Array in the following way to get an array with unique values:

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']
click below button to copy the code. By JavaScript tutorial team

The native method filter will loop through the array and leave only those entries that pass the given callback function onlyUnique.

onlyUnique checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied. This solution works without any extra library like jQuery or prototype.js.

It works for arrays with mixed value types too.

For old Browsers (<ie9), that do not support the native methods filter and indexOf we can find work arounds in the MDN documentation for filter and indexOf . If we want to keep the last occurrence of a value, simple replace indexOf by lastIndexOf. With ES6 it could be shorten to this:

// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i); 

// unique is ['a', 1, 2, '1']
click below button to copy the code. By JavaScript tutorial team

ES6 has a native object Set to store unique values. To get an array with unique values we could do now this:

var myArray = ['a', 1, 'a', 2, '1'];

let unique = [...new Set(myArray)]; 

// unique is ['a', 1, 2, '1']
click below button to copy the code. By JavaScript tutorial team

The constructor of Set takes an iterable object, like Array, and the spread operator ... transform the set back into an Array.

Solution 2:

Updated answer for ES6/ES2015: Using the Set operator, the single line solution is:

var items = [4,5,4,6,3,4,5,2,23,1,4,4,4]
var uniqueItems = Array.from(new Set(items))
click below button to copy the code. By JavaScript tutorial team

Which returns

[4, 5, 6, 3, 2, 23, 1]
click below button to copy the code. By JavaScript tutorial team

This can also be shortened using spread operator , like

var uniqueItems = [...new Set(items)]
click below button to copy the code. By JavaScript tutorial team

Solution 3:

We can also use underscore.js .

console.log(_.uniq([1, 2, 1, 3, 1, 4]));
<script src="http://underscorejs.org/underscore-min.js"></script>
click below button to copy the code. By JavaScript tutorial team

Run code snippet Expand snippet which will return:

[1, 2, 3, 4]

Solution 4:

We have since found a nice method that uses jQuery

arr = $.grep(arr, function(v, k){
    return $.inArray(v ,arr) === k;
});

click below button to copy the code. By JavaScript tutorial team

Solution 5:

This prototype getUnique is not totally correct, because if we have a Array like: ["1",1,2,3,4,1,"foo"] it will return ["1","2","3","4"] and "1"

Array.prototype.unique = function(a){
    return function(){ return this.filter(a) }
}(function(a,b,c){ return c.indexOf(a,b+1) < 0 });
click below button to copy the code. By JavaScript tutorial team

using:

var foo;
foo = ["1",1,2,3,4,1,"foo"];
foo.unique();
click below button to copy the code. By JavaScript tutorial team

The above will produce ["1",2,3,4,1,"foo"].


Related Searches to javascript tutorial - Unique values in an array