码迷,mamicode.com
首页 > 其他好文 > 详细

数组去重和数组拍平

时间:2014-08-10 18:10:20      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   数据   for   ar   

1 简单数组去重

 1 Array.prototype.unique = function(){
 2          var obj={},res=[]; //temp用于存放去重后的元素
 3 
 4          for(var i=0;i<this.length;i++){
 5              var temp = this[i];
 6              if(!obj[ (typeof temp) + temp ]){
 7                  res.push(temp);
 8                  obj[ (typeof temp) + temp ] =true;
 9              }
10          }
11 
12          return res;
13     };
14     var arr = [1,2,1,‘1‘,‘2‘,3];
15     console.log(arr.unique());

 

2 多种数据类型的数组去重

 1 Array.prototype.multiUnipque = function (){
 2         //判断对象类型的方法
 3         var isEqual = function (obj1, obj2){
 4             //判断两个对象的地址是否一样,地址一样则必相等,这里只为了优化性能
 5             if(obj1 === obj2){
 6                 return true;
 7             }
 8             if(typeof(obj1)=="object"&&typeof(obj2)=="object"){
 9                 //判断两个对象类型一致且为object类型
10                 var count= 0;
11                 for(var attr in obj1){
12                     count++;
13                     if(!isEqual(obj1[attr],obj2[attr])){
14                         return false;
15                     }
16                 }
17                 for(var attr in obj2){
18                     count--;
19                 }
20                 return count==0;
21             }else if(typeof(obj1)=="function"&&typeof(obj2)=="function"){
22                 //判断两个对象类型一致且为function类型
23                 if(obj1.toString()!==obj2.toString()){
24                     return false;
25                 }
26             }else {    //判断两个对象类型不一致,再判断值是否相等
27                 if(obj1!=obj2){
28                     return false;
29                 }
30             }
31             return true;
32         }
33 
34         //temp作为传入数组arr的备份,在不改变原数组的基础上进行去重操作
35         var temp=this.slice(0);
36         for(var i=0;i<temp.length;i++){
37             for(var j=i+1;j<temp.length;j++){
38                 if(isEqual(temp[j],temp[i])){
39                     temp.splice(j,1);//删除该元素
40                     j--;
41                 }
42             }
43         }
44         return temp;
45     }
46 
47     var arr = [1,2,1,‘1‘,‘2‘,3,[1],[1],{a:1,b:2},{a:1},{a:1,b:2}];
48     console.log(arr.multiUnipque());

3 应用:数组拍平

用数组方法实现如下:

 var arr = [1, [2, [3, 4]]];

arr.toString().split(",").map(function(item){ return +item; }) ;

用模拟方法实现:

数组去重和数组拍平,布布扣,bubuko.com

数组去重和数组拍平

标签:style   blog   color   os   io   数据   for   ar   

原文地址:http://www.cnblogs.com/guoyongfeng/p/3903047.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!