ES3-ES6 array deduplication method

ES3 array deduplication method
1. For loop deduplication
Give the first item of the old array to the new array, then compare each item of the old array with the first item of the new array, and add it to the new array if there is no repetition, if there is repetition just leave out
  let arr = [3, 5, 2, 6, 8, 5, 7, 2];
  let newArray = [arr[0]];
  function newArray(arr) {
    for (let i = 1; i < arr .length; i++) { //traverse each item of arr
      let isRepeat = false;
      for (let j = 0; j < newArray.length; j++) {//traverse each item of newArray
        if(arr[i] === newArray[j]){
          isRepeat = true;
          break;
        }
      }
      if(!isRepeat){
        newArray.push(arr[i]);
      }
    }
    return newArray;
  }

2. For loop deduplication
  Compare each item in the array with each item after it, and add it to a new empty array without repetition
  var arr = [3, 5, 2, 6, 8, 5, 7 , 2];
  var newAarry = [];
  for (var i = 0; i < arr.length; i++) {
    for (var j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) {
        j=++i;
      }
    }
      newAarry.push(arr[i]);
  }

ES5 array deduplication method

3. indexOf index comparison method
  Declare a new array and an old array, traverse each item of the old array and compare it with each subsequent item to see if there is the same, and add it to the new array if it does not exist.
  let arr = [3, 5, 2, 5, 7, 23, 5, 7];
  let newArr = [];
  arr.forEach((val,index)=>{
    if(arr.indexOf(val,index+1 )== -1){
      newArr.push(val)
    }
  })

4. indexOf index search method
  Declare an old array and a new array, add the first item of the old array to the new array, see if each item of the old array exists in the new array, and add it to the new
  array .
  let arr = [3, 5, 2, 5, 7, 23, 5, 7];
  let newArr = [arr[0]];
  arr.forEach((val,index)=>{
    if(newArr.indexOf(val )== -1){
      newArr.push(val)
    }
  })

ES6 array deduplication method

5.set method
  Declare an array with repeated values, convert the array into an object without repeated values ​​through the set constructor, and then convert the object into an array
  let arr = [3, 5, 2, 5, 7, 23, 5, 7];
  let obj = new Set(arr)
  let newArr = Array.from(obj)

6. Spread operator... 

  Convert the array to a comma-separated parameter sequence, with functions such as merging and copying arrays
  let arr = [3, 5, 2, 6, 5, 7];
  let newArr = [...new Set(arr)];

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325318982&siteId=291194637