js數組去重問題

1. 雙層循環:外層循環,內層比較值;javascript

(1)利用splice直接在原數組進行操做java

Array.prototype.delRepeat = function (){
 var arr = this;
 var i,j,len = arr.length;
 for(i = 0; i < len; i++){
  for(j = i + 1; j < len; j++){
   if(arr[i] == arr[j]){
    arr.splice(j,1);
    len--;
    j--;
   }
  }
 }
 return arr;
};
var a = [1,2,4,4,5,6,5,3,2,4,9,4,1,2,9,1,1];
console.log(a.delRepeat()); //[1, 2, 4, 5, 6, 3, 9]  

2. 利用對象的屬性不能相同的特色進行去重 數組

Array.prototype.delRepeat = function (){
 var arr = this;
 var i;
 var obj = {};
 var result = [];
 for(i = 0; i< arr.length; i++){
  if(!obj[arr[i]]){ 
   obj[arr[i]] = 1;
   result.push(arr[i]);
  }
 }
 return result;
};
var a = [1,2,4,4,5,6,5,3,2,4,9,4,1,2,9,1,1];
console.log(a.delRepeat()); //[1, 2, 4, 5, 6, 3, 9]  

3. 利用ES6的setthis

 (1)利用Array.from將Set結構轉換成數組prototype

function delRepeat(array){
 return Array.from(new Set(array));
}
var a = [1,2,4,4,5,6,5,3,2,4,9,4,1,2,9,1,1];
console.log(a.delRepeat()); //[1, 2, 4, 5, 6, 3, 9]

 

 (2)拓展運算符(...)內部使用for...of循環對象

let arr = [1,2,4,4,5,6,5,3,2,4,9,4,1,2,9,1,1];
let resultArr = [...new Set(arr)]; 
console.log(resultArr); 

4.藉助indexOf()方法,判斷此元素在該數組中首次出現的位置下標與循環的下標是否相等blog

(1)不借助新數組,使用splice();ip

var ar = [1,2,4,4,5,6,5,3,2,4,9,4,1,2,9,1,1];
function delRepeat(arr){
  for (var i = 0; i < arr.length; i++) {
        if (arr.indexOf(arr[i]) != i) {
            arr.splice(i,1);//刪除數組元素後數組長度減1後面的元素前移
            i--;//數組下標回退
        }
    }
     return arr;
 }

console.log( delRepeat(ar)); // [1, 2, 4, 5, 6, 3, 9]

(2)藉助新數組;element

var ar = [1,2,4,4,5,6,5,3,2,4,9,4,1,2,9,1,1];
function delRepeat(arr) {
 var result = [];
 for (var i = 0; i < arr.length; i++) {
  if (arr.indexOf(arr[i]) == i) {
  result.push(arr[i]);
  }
}
 return result;
}

console.log(delRepeat(ar)); // [1, 2, 4, 5, 6, 3, 9]  

(3)藉助新數組  判斷新數組中是否存在該元素若是不存在則將此元素添加到新數組中io

Array.prototype.delRepeat = function(){
    var newArr = [];
    for(var i = 0; i < this.length; i++){
        if(newArr.indexOf(this[i])== -1){
            newArr.push(this[i]);
        }
    }
    return newArr;
}
var arr = [1,2,4,4,5,6,5,3,2,4,9,4,1,2,9,1,1];
console.log(arr.delRepeat()); // [1, 2, 4, 5, 6, 3, 9]  

5. 利用數組中的filter方法

var arr = ['a','f','b','p','e','a','o','f'];
var result = arr.filter(function(element,index,self){
  return self.indexOf(element) === index;
});
console.log(result); //["a", "f", "b", "p", "e", "o"]

相關文章
相關標籤/搜索