javascript|js 数组去重(单元素和对象数组)

源码

//方案1,旧方案 Array.prototype.unique = function(key) { var arr = this; var n = [arr[0]]; for (var i = 1; i < arr.length; i++) { if (key === undefined) { if (n.indexOf(arr[i]) == -1) n.push(arr[i]); } else { inner: { var has = false; for (var j = 0; j < n.length; j++) { if (arr[i][key]!==undefined && arr[i][key] === n[j][key]) { has = true; break inner; } } } if (!has) { n.push(arr[i]); } } } return n; }//方案2,相比方案一,少了一层循环,提高效率,逻辑更加清晰 Array.prototype.uniqueTree = function(key) { var res = []; var json = {}; var arr = this; for (var i = 0; i < arr.length; i++) { if (arr[i][key]===undefined||json[arr[i][key]]===undefined) { res.push(arr[i]); json[arr[i][key]] = 1; } } return res; };

使用方法:
[1,2,3,4,3,2].unique() //[1,2,3,4]

[{a:1},{a:2},{a:1}].unique('a') //[{a:1},{a:2}]

    推荐阅读