看了 从JavaScript 数组去重谈性能优化,想到取出js数组中的重复元素
需求如题,如[3,'hello',5,6,4,3,'hello'],取出[3,'hello']
有好的方式来唠唠呗
var a = [3, 'hello', 5, 6, 4, 3, 'hello']; Array.prototype.duplicate=function() { var tmp = []; this.concat().sort().sort(function(a,b){ if(a==b && tmp.indexOf(a) === -1) tmp.push(a); }); return tmp; } alert(a.duplicate());
function duplicates (list) { res = []; list.forEach(function(item, index) { rest = list.slice(index + 1); if (rest.indexOf(item) > 0 && res.indexOf(item) < 0) { res.push(item); } }); return res; } // test var testList1 = [3,'hello',5,6,4,3,'hello']; var testList2 = [3,'hello',5,6,4,3,'hello', 'hello', 3, 3, 5, 5]; var result1 = duplicates(testList1); var result2 = duplicates(testList2); console.log('repeat only once: ', result1); console.log('multiple repetition: ', result2);
//适用基础数据类型(空间换时间的方案) function duplicates(list) { var cache = {}, own = Object.prototype.hasOwnProperty, r = [] ; for (var i = list.length; --i>=0; ){ var item = list[i], key = item.toString() ; if (!own.call(cache, key)) { cache[key] = 1; } else { r.push(item); } } return r; }
任何时候,如非必要,不要破坏原型,即使是做es5的shim;2L sort combo蛮赞的,不过indexOf没有考虑古董client;4L cache key和判断cache做的有点多了感觉,结合一下或许会好一些。
var a = [3, 'hello', 5, 6, 4, 3, 'hello']; function duplicate(source) { var ret = [], cache = []; source.concat().sort().sort(function (a, b) { if (a == b) { var key = typeof(a) + ":" + a; if (!cache[key]) { cache[key] = true; ret.push(a); } } }); return ret; } // test console.log(duplicate(a));
如果数据集比较大的话,可以考虑不建立cache,使用快排走index维护重复元素列表。
function deRepeat(arr){
var temp = [],obj={};
for(var i=0,len=arr.length;i<len;i++){
!obj[arr[i]]?obj[arr[i]]=1:temp2.push(arr[i]);
}
return temp;
}
console.log(deRepeat([1,2,1,4,3,5,2,4]));
function remove(arr) { var a = [] var b = [] for(var i = 0; i <arr.length;i++) { if(a.indexOf(arr[i]) == -1) { a.push(arr[i]) } else { b.push(arr[i]) } } return { a : a, b :b } }
function remove(arr) {
var a = []
var b = []
for(var i = 0; i <arr.length;i++) {
if(a.indexOf(arr[i]) == -1) {
a.push(arr[i])
} else {
b.push(arr[i])
}
}
return {
a : a,
b :b
}
}
©2012-2013 F2E.im Powered by Tornado on Linode , All rights reserved.
Bitcoin Donation: 1MqzGbsAufs3gCFEqqTM9WBNnRmVFu7HWH