JavaScript中关于数组去重复的方式很多,下面汇总了常见的几种实现方式。
1 /*实现一:基于原型扩展*/ 2 Array.prototype.removeDuplicate = function() { 3 var arrObj = {}, 4 newArr = [], 5 len = this.length; 6 for(var i = 0; i < len; i++) { 7 var value = this[i], 8 type = (typeof value) + value; 9 if(arrObj[type] === undefined) { 10 newArr.push(value); 11 arrObj[type] = len; 12 } 13 } 14 return newArr; 15 } 16 17 var s = [1, 1, 2, 3, 4, 5, 4, 3, 4, 4, 5, 5, 6, 7]; 18 s.removeDuplicate(); //[1, 2, 3, 4, 5, 6, 7] 19 20 /*实现二:去除重复后数组为字符串*/ 21 var removeDuplicate = function(array) { 22 array = array || []; 23 var arrObj = {}, 24 len = array.length; 25 for(var i = 0; i < len; i++) { 26 var data = array[i]; 27 if(typeof(arrObj[data]) === ‘undefined‘) { 28 arrObj[data] = 1; 29 } 30 } 31 array.length = 0; 32 for(var arr in arrObj) { 33 array[array.length] = arr; 34 } 35 return array; 36 } 37 38 var s = [1, 1, 2, 3, 4, 5, 4, 3, 4, 4, 5, 5, 6, 7]; 39 removeDuplicate(s); //["1", "2", "3", "4", "5", "6", "7"] 40 41 /*实现三:去除重复后数组为数字*/ 42 var removeDuplicate = function(array) { 43 var str = []; 44 for(var i = 0, len = array.length; i < len; i++) { 45 !RegExp(array[i], ‘g‘).test(str.join(‘,‘)) && (str.push(array[i])); 46 } 47 return str; 48 } 49 50 var s = [1, 1, 2, 3, 4, 5, 4, 3, 4, 4, 5, 5, 6, 7]; 51 removeDuplicate(s); //[1, 2, 3, 4, 5, 6, 7] 52 53 /*实现四:hashtable的结构记录已有的元素,这样就可以避免内层循环*/ 54 var removeDuplicate = function(array) { 55 var hash = {}, 56 newArr = []; 57 for(var i = 0, elem; (elem = array[i]) != null; i++) { 58 if(!hash[elem]) { 59 newArr.push(elem); 60 hash[elem] = true; 61 } 62 } 63 return newArr; 64 } 65 66 var s = [1, 1, 2, 3, 4, 5, 4, 3, 4, 4, 5, 5, 6, 7]; 67 removeDuplicate(s); //[1, 2, 3, 4, 5, 6, 7]
上面四种实现方式中,都实现了数组去重复的需求,但在实现方式和性能上面存在一定的差异,其中实现四的方式效率最高。
时间: 2024-10-28 21:54:21