js配列デ重量(単一要素と対象配列)
1240 ワード
ソース
// 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}]