Skip to content

Instantly share code, notes, and snippets.

@jasonweng
Forked from fundon/array_distinct.js
Created December 19, 2011 14:00
Show Gist options
  • Save jasonweng/1497361 to your computer and use it in GitHub Desktop.
Save jasonweng/1497361 to your computer and use it in GitHub Desktop.
array distinct , JavaScript
//http://lijing00333.wordpress.com/2011/02/08/%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D%E2%80%94%E2%80%94%E4%B8%80%E9%81%93%E5%89%8D%E7%AB%AF%E6%A0%A1%E6%8B%9B%E8%AF%95%E9%A2%98/
// [1,2,2,2,3,4,5].toString().match(/(\d)(?!.*,\1)/g);
Array.prototype.distinct = function() {
var o = {}, i = 0, l = this.length;
for (; i < l;) {
if (!o.hasOwnProperty(this[i])) {
o[this[i++]] = 1;
} else {
this.splice(i, 1);
l--;
}
}
return this;
}
var a = [1, 2, 3, 4, 5, 2, 3, 4, 6, 7, 8];
console.log(a.distinct());
var a = [10, 0, 0, 1, 2, 3, 4, 5, 2, 3, 4, 6, 7, 8, 10];
console.log(a.distinct());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment