Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
javascript.array.unique
/**
* 数组去重
* @param key
* @returns arr
* @example var newArr = arr.unique('nickname');
*/
Array.prototype.unique = function (key) {
var key = key || null, temp;
var arr = this,
hash = {};
this.forEach(function (v) {
// 根据传入的key判断哪个作为唯一
// 如果没有输入key,那就不是obj
key ? temp = v[key] : temp = v;
// 用v作为hash的key,这样重复的key会被覆盖的
hash[temp] = v;
});
// 恢复数组
arr = [];
for(var i in hash) {
arr.push(hash[i]);
}
return arr;
}
// 循环去重方式
function unique (arr) {
var n = [];
arr.forEach(function (v) {
n.indexOf(v) === -1 && n.push(v);
});
return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment