Last active
August 29, 2015 13:57
-
-
Save think2011/9775618 to your computer and use it in GitHub Desktop.
javascript.array.unique
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 数组去重 | |
* @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