码迷,mamicode.com
首页 > 编程语言 > 详细

数组去重复算法

时间:2018-04-02 20:23:52      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:turn   push   ==   define   nbsp   否则   遍历   低版本   --   

1.遍历法

  var ary=[1,23,12,12,1,12,32,1,1];
  function noRepetition(ary){
//    1.创建新数组
    var newAry=[];
//    2.遍历老数组,拿到每个值,看新数组有这个值吗,没有添加进去,
    for(var i=0;i<ary.length;i++){
      var cur=ary[i];
      if (newAry.indexOf(cur)==-1){     indexOf IE8以前不支持,
        newAry.push(cur)
      }
    }
//    3.返回新的数组
    return newAry;
  }
  var result=noRepetition(ary);
  console.log(result)                 
//方法不改变元素组

兼容版:

//兼容IE低版本的indexOf方法
if(!Array.prototype.indexOf){ Array.prototype.indexOf=function(para){ var result=-1; var temp=para; if (!this.length){ return result } // 谁调用我,我就便利谁 for(var i=0;i<this.length;i++){ var cur=this[i] if (cur==temp){ result=temp; break; } } return result } }

2.对象键值对

  var ary=[1,23,12,12,1,12,32,1,1];
function noRepetition(ary){
  var obj={};
//  1.拷贝一份原数组
  var temp=ary.slice(0);
//  2.遍历
  for(var i=0;i<temp.length;i++){
    var cur=temp[i];
//    如果对象obj[cur]==undefined表示,对象没有该属性,添加该属性
    if (!obj[cur]){
      obj[cur]=cur;
    }else{
//      否则,证明对象中有该属性,temp数组删除重复元素
      temp.splice(i,1);
      i--;
    }
  }
  return temp;
}
  var result=noRepetition(ary);
  console.log(result)

3.排序去重复法

  var ary=[1,1,2,1,33,22,75,15,2,2,1,2,1,3,4,5,5,75];
  function noRepetition(ary){
    var result=[];
//    1.排序
    var temp=ary.sort(function(a,b){
      return a-b
    });
//    2.遍历排好序的数组
    for(var i=0;i<temp.length;i++){
//      3.当 当前值不等于后一项的值时
      if (temp[i]!==temp[i+1]){
//        4.空数组中添加当前项
//        注意,当我们最后一项时,他的后一项时undefined的,所以最后一项可以添加进来
        result.push(temp[i])
      }
    }
    return result
  }
  console.log(noRepetition(ary))

 

数组去重复算法

标签:turn   push   ==   define   nbsp   否则   遍历   低版本   --   

原文地址:https://www.cnblogs.com/liangfc/p/8695741.html

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