JavaScript array common way to achieve weight

JavaScript array of ways to re

Code deduplication array, generally during the interview often ask to or generally requires an array of deduplication method of handwriting

A, ES5 most commonly used for nesting for use, and then to re-splice

function unique(arr){            
  for(var i=0; i<arr.length; i++){
    for(var j=i+1; j<arr.length; j++){
      //第一个等同于第二个,splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组
      if(arr[i]==arr[j]){
        arr.splice(j,1);
        j--;
      }
    }
  }
return arr;
}
var arr = [1,2,3,4,5,6,2,4,6,8];
console.log(unique(arr))
复制代码

Second, using the Set deduplication ES6 (Set method for ES6)

function unique (arr) {
  return Array.from(new Set(arr))
}
var arr = [1,2,3,4,5,6,2,4,6,8];
console.log(unique(arr))
复制代码

Compatibility is not considered, then this deduplication method code is minimal, the ECMAScript entry. 6

Third, the use indexOf deduplication

var arr = [1,3,4,5,6,7,4,3,2,4,5,6,7,3,2];
function unique(){
  var newArr = [];
  for (var i = 0; i < arr.length; i++) {
    if (newArr.indexOf(arr[i]) == -1 ) {
      newArr.push(arr[i]);
    }
  }
  console.log(newArr);
}
unique(arr);
复制代码

Result the indexOf () method if the retrieved value does not match, it returns -1.

Fourth, the use sort ()

var arr = [1,3,4,5,6,7,4,3,2,4,5,6,7,3,2];
function unique2(arr){
  arr.sort();
  var newArr = [arr[0]],
      len = arr.length;
  for(var i = 1; i < len; i++){
    if(arr[i] !== newArr[newArr.length - 1] ){
      newArr.push(arr[i]);
    }
  }
  return newArr;
}
console.log( unique2(arr) );
复制代码

Fifth, the use of object properties deduplication

Each element of the array is taken out of the original, and then access the object property, it shows if there is repeated

function unique(arr){
  var res =[];
  var json = {};
  for(var i=0;i<arr.length;i++){
    if(!json[arr[i]]){
      res.push(arr[i]);
      json[arr[i]] = 1;
    }
  }
  return res;
}
var arr = [1,3,4,5,6,7,4,3,2,4,5,6,7,3,2];
console.log(unique(arr))
复制代码

Sixth, the method includes the use of an array prototype object

function unique(arr){
 var res = [];
 for(var i=0; i<arr.length; i++){
  if( !res.includes(arr[i]) ){ // 如果res新数组包含当前循环item
   res.push(arr[i]);
  }
 }
 return res;
}
console.log(unique([1,1,2,3,4,5,3,2,3,6,7,4]));
复制代码

Guess you like

Origin blog.csdn.net/weixin_34061482/article/details/91399347