四. JavaScript 数组去重

双重循环

  数组去重,不就是比较数组元素,去掉重复出现的么。最原始的方式不正是双重循环进行比较处理嘛

//测试数据
var test = [1,2,2,10,'1','a','a','b','@','@'];
 
console.log(unique1(test));  //[1,2,10,'1','a','b','@']
 
function unique1(target) {   //双层循环比较数组元素进行去重
  var res = [];      //存放数据
  for(var i = 0 ; i<target.length ; i++){
 
    for(var j = 0,resLen = res.length ; j < resLen ; j++){
      if(target[i] === res[j]){  //如果有相同的数据,则break
        break;
      }
    }
 
    if(j === resLen){   //res中没有相同的数据,则存放
      res.push(target[i])
    }
  }
  return res;
}

indexof优化内层循环

  在本栗中使用indexof优化内层循环。indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1

var test = [1,2,2,10,'1','a','a','b','@','@'];
console.log(unique2(test)); //[1,2,10,'1','a','b','@'] function unique2(target) { //indexof简化内层循环 var res = []; //存放数据 for(var i = 0 ; i<target.length ; i++){ if(res.indexOf(target[i]) < 0) //如果res中不存在该元素,返回-1 res.push(target[i]) } return res; }

对象键值对优化内层循环

  对象的键不同重复,这个特性可以用来判断重复元素

  //测试数据
    var test = [1,2,2,10,'1','a','a','b','@','@'];

    console.log(unique3(test));  //[1,2,10,'a','b','@']   因为对象键是字符串 所以此种方式会认为 1 和 '1' 是相同的

    function unique3(target) {  //对象键值的方式
      var obj = {};
      var res = target.filter(function(value,index){
        return obj.hasOwnProperty(typeof value + value ) ? false : (obj[typeof value + value] = true);
 }) return res; }

filter优化外层循环

  在本栗中使用filter优化外层循环。filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

var test = [1,2,2,10,'1','a','a','b','@','@'];
 
console.log(unique5(test));  //[1,2,10,'1','a','b','@']
 
function unique5(target) {   //filter简化外层循环
  var res = target.filter(function(value,index,array){
    return target.indexOf(value) === index    //第一次出现则返回true
  })
  return res
}

Set去重

  ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。这种特性用来数组去重,十分的方便。

  //测试数据
    var test = [1,2,2,10,'1','a','a','b','@','@'];

    var unique6 = (target) => [...new Set(target)];  //干脆利落

    console.log(unique6(test));  //[1,2,10,'1','a','b','@']

猜你喜欢

转载自www.cnblogs.com/hy-space/p/8945797.html