Skip to content

Instantly share code, notes, and snippets.

@lushijie
Last active December 28, 2017 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lushijie/1387e0d5e199e92c736cea9f6533239d to your computer and use it in GitHub Desktop.
Save lushijie/1387e0d5e199e92c736cea9f6533239d to your computer and use it in GitHub Desktop.
数组去重
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