zoukankan      html  css  js  c++  java
  • 数组去重的方法总结

    方法一 // var arr = [1, 'a', 'a', 'b', 'd', 'e', 1, 0]; // Array.prototype.unique1 = function () { // var res = [this[0]];//获取数组的第一个元素 res = [1] // for (var i = 1; i < this.length; i++) { // var repeat = false;//假设最开始没有重复 // for (var j = 0; j < res.length; j++) { // if (this[i] == res[j]) { //i=1 this[1]=a res= [1] res.length =1 res= [1,'a'] // repeat = true; //i=2 this[2]=a res= [1,'a'] res.length =2 res= [1,'a'] // break; //i=3 this[3]=b res= [1,'a'] res.length = 2 res= [1,'a','b'] // } //i=4 ...... // } // if (!repeat) { // res.push(this[i]); // } // } // return res; // } // var arr = [1, 'a', 'a', 'b', 'd', 'e', 1, 0]; // console.log(arr.unique1()); 方法二 //如果对象属性不存在,不会报错,返回undefined //直接设置一个不存在的属性,就直接相当于给对象添加了一个属性(动态属性) // Array.prototype.unique3 = function () { // var res = []; // var json = {}; // for (var i = 0; i < this.length; i++) { // if (!json[this[i]]) { //i=0 this[i]=1 json[1]=undefined res = [1] json={1:1} // res.push(this[i]); //i= 1 this[i]=a json[a]=undefined res = [1,'a'] json={1:1,"a":1} // json[this[i]] = 1; //i =2 this[i]= a json[a]=1 res = [1,'a'] json={1:1,"a":1} //i=3 this[i]= b json[b]=undefined res= [1,'a','b'] json={1:1,"a":1,"b":1} // } // } // return res; // } // var arr = [1, 'a', 'a', 'b', 'd', 'e', 1, 0]; // console.log(arr.unique3()); 方法三 // 简单粗暴法 (Set): /* let arr = [1, 1, 3, 3, 2, 2, 5, 5, 6, 6, 7, 7]; let nowArr = [] Array.prototype.unique1 = function () { let newArr = [...new Set(this)]; return newArr; } let arr1 = arr.unique1(); console.log(arr); console.log(arr1); */ 方法四 /* let arr = [1, 1, 3, 3, 2, 2, 5, 5, 6, 6, 7, 7]; let nowArr = [] Array.prototype.unique2 = function () { let newArr = [this[0]]; //一个新的临时数组 for (let i = 1; i < this.length; i++) { //从第二项开始遍历 if (newArr.indexOf(this[i]) == -1) { // indexOf: 可返回某个指定的值在数组(字符串)中首次出现的位置。 newArr.push(this[i]); // 返回值:-1 说明该数组中没有出现过这个数 push到临时数组里去 } // 返回值 !-1(为该值在数组中的下标) 说明临时数组中已存在该值 就忽略 } return newArr; } let arr1 = arr.unique2(); console.log(arr); console.log(arr1); */ 方法五 // 优化遍历数组法 // var arr = [1, 3, 4, 5, 3, 4, 8, 9, 8, 4]; // for (var i = 0; i < arr.length; i++) { // for (var j = i + 1; j < arr.length; j++) { // if (arr[i] == arr[j]) { // arr.splice(j, 1); // j--; // } // } // } // console.log(arr) //[1,3,4,5,8,9]
  • 相关阅读:
    hive中named_struct构造和使用
    hive非分区表导入csv数据
    hive常用的日期函数
    hive mapreduce reducer 调优
    Hive Analytics Functions row_number rank over partition by
    skip-grant-tables
    VC中的字符串转换宏
    CMAKE的使用
    VSCODE C/C++配置
    libcurl,多线程,gzip,共享DNS
  • 原文地址:https://www.cnblogs.com/hhmmpp/p/11070254.html
Copyright © 2011-2022 走看看