Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
数组去重
Array.prototype.unique = function() { //查找索引 indexOf
var ret = []
for (var i = 0; i < this.length; i++) {
if (ret.indexOf(this[i]) == -1) {
ret.push(this[i])
}
}
return ret;
}
Array.prototype.unique = function() { //借用对象
var ret = [], obj = {};
for (var i = 0; i < this.length; i++) {
if (!obj[this[i]]) {
obj[this[i]] = true;
ret.push(this[i])
}
}
return ret;
}
Array.prototype.unique = function() { //sort->filter
return this.sort((a,b) => a - b ).filter((e,i,a) => a[i] !== a[i - 1]);
}
Array.prototype.unique = function() { //借用set
return [...new Set(this)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment