I think
[1,4,5,1,5].filter(function(x, n, self) {
return self.indexOf(x) == self.lastIndexOf(x)
})
A probably more efficient hash-based version using underscore:
a =[1, 2, 3, 3, 4, 2, 1, 5]
uniqs = _.chain(a).countBy().pairs().filter(function(x) {
return x[1] == 1
}).pluck(0).value()
or plain javascript:
a = [1, 2, 3, 3, 4, 2, 1, 5]
hash = {}
a.forEach(function(x) {
hash[x] = (Number(hash[x]) || 0) + 1
});
uniq = Object.keys(hash).filter(function(n) {
return hash[n] == 1
});
Note however, that this would convert array values to strings (the result will be ["4","5"]
).
If you're happy with the array being sorted, you can also do it like this:
a = [1, 2, 3, 3, 4, 2, 1, 5]
uniq = a.sort().filter(function(x, n, self) {
return x != self[n - 1] && x != self[n + 1];
});
//[4, 5]
The second and third methods have a serious limitation that they only work with primitive values - you cannot "uniquify" an array of objects. The first function works just fine:
x = {x:1}; y = {y:1}; a = [x, y, x, x];
uniq = a.filter(function(x, n, self) {
return self.indexOf(x) == self.lastIndexOf(x)
})
// {"y":1}
For those curious, performance tests (quite inconsistent in different browsers): http://jsperf.com/efficient-unique/2