1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>javascript数组去重算法-----3</title> 6 </head> 7 <body> 8 <script> 9 var arr = [1,1,2,2,3,2,2,3,3,1,1,4,4,5,6]; 10 function unique(array){ 11 var n = []; 12 var a = {}; 13 for (var i = 0; i < array.length; i++) { 14 if (!a[array[i]]) { 15 a[array[i]] = true; 16 n.push(array[i]) 17 }; 18 } 19 return n 20 } 21 var cc =unique(arr); 22 console.log(cc) 23 //利用对象的特性,存在的向设为true,并且添加的数组,否则不添加 24 </script> 25 </body> 26 </html>
扩展:1模块化,2返回一个对象,对象中包括已去重的数组和每个数字的多少;代码如下:
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <script> 9 var a = [1,2,3,4,5,6,6,6,7,7,7,3,3,3]; 10 11 var uniqueModule = (function(){ 12 function unique(arr){ 13 var n = []; 14 var hash = {}; 15 for(var i = 0;i<arr.length;i++){ 16 if(!hash[arr[i]]){ 17 hash[arr[i]] = 1; 18 n.push(arr[i]); 19 }else{ 20 hash[arr[i]]++; 21 } 22 } 23 return { 24 n:n, 25 hash:hash 26 }; 27 } 28 return { 29 unique:unique 30 } 31 }()); 32 console.log(uniqueModule.unique(a)); 33 </script> 34 </body> 35 </html>