Javascript Array distinct()
Array.prototype.distinct = function () { var known = {}; var result = []; this.forEach(item => {/* ww w . j av a 2s . co m*/ if (!known[item]) { known[item] = true; result.push(item); } }); return result; };
/**/*from w w w . java2 s .c o m*/ * author: oldj * blog: http://oldj.net */ Array.prototype.distinct = function () { var d = {}, i; this.push(d); while ((i = this.shift()) != d) { if (!d.hasOwnProperty(i)) { this.push(i); d[i] = 1; } } return this; };
Array.prototype.distinct = function() { var ret = []; for (var i = 0; i < this.length; i++) { for (var j = i + 1; j < this.length; ) { if (this[i] === this[j]) { ret.push(this.splice(j, 1)[0]); } else {/*ww w . ja va 2 s . c o m*/ j++; } } } return ret; }; console.log([1, 2, 3, 4, 4, "4", 5].distinct());
// Way 1;//from ww w . j av a2 s .co m Array.prototype.distinct = function(){ for(var i = 0; i< this.length; i++){ var n = this[i]; this.splice(i, 1); if(this.indexOf(n) < 0){ this.splice(i,1,n); } } return this; } Array.prototype.distinct2 = function(){ var _self = this; var _a = this.concat().sort(); console.log(_a); _a.sort(function(a,b){ console.log("a: "+ a, "b: "+ b); if(a == b){ var n = _self.indexOf(a); _self.splice(n, 1); } }); return _self; }
Array.prototype.distinct = function() { var ret = [];//from w w w. j a va2s .c o m for (var i = 0; i < this.length; i++){ for (var j = i+1; j < this.length;) { if (this[i] === this[j]) { ret.push(this.splice(j, 1)[0]); } else { j++; } } } return ret; }; //for test var a = ['a','b','c','d','b','a','e','d','b','a','e']; var b = a.distinct(); console.log(a); console.log(b);
Array.prototype.distinct = function () { var n = {}, r = []; for (var i = 0; i < this.length; i++) { if (!n[this[i]]) { n[this[i]] = true;/*from www . j a v a 2s .c o m*/ r.push(this[i]); } } return r; }
Array.prototype.distinct = function () { return this.filter(function (element, position, self) { return self.indexOf(element) == position; });/*from w w w .j a v a 2 s . c om*/ };