当前位置:网站首页>Number array de duplication in JS

Number array de duplication in JS

2022-06-25 23:56:00 wen_ Wen Wen

 //  Method 1:  ES6 Medium Set Data structure method 
 function arrRemoval(array) {
  //  let set = Array.from(new Set(array));
   let set = [...new Set(array)];
   return set;
 }

// Method 2: Define an empty new array , Each time, judge whether the new array contains the current element , If not, add 
 function arrRemoval(array) {
   let result = [];
   array.forEach((ele,ind) =>{
      if(!result.includes(ele)) {
        result.push(ele);
      }
   })
   return result;
 }

 // Method 3: indexOf Law , indexof(item): Returns the index of the first element found in the array 
 function arrRemoval(array) {
   let result = [];
   result = array.filter((ele,ind) =>{
      return array.indexOf(ele)===ind; 
   })
   return result;
 }

 // Method 4: reduce Law : 
 function arrRemoval(array) {
     let result = [];
     //  Define the initial pre by []  
     result = array.reduce( function(pre, item){
       // return pre.indexOf(item)!==-1 ? pre : pre.concat(item);
       return pre.indexOf(item)!==-1 ? pre : [...pre,item];
     }, [])
    return result;
 }

//  Method 5: Leverage the key Non repeatable features , If key Repetition is set later value Cover the front of value
 function arrRemoval(array) {
      let result = {};
      //  Define the initial pre by []  
      array.forEach((ele,ind) => {
        result[ele] = ind;
      });
      // console.log(Object.keys(result));   //["1", "2", "3", "4", "5"]
      
      return Object.keys(result).map((ele,ind)=>{
        // ~~ The returned result is numeric 
        // return ~~ele;
        return parseInt(ele);
      })
 }
 //  Method 6:  Prioritize ,  Then compare the i Xiang He i+1 term ,
 function arrRemoval(array) {
      let result = [];
      array.sort();
      for(let i=0;i<array.length;i++) {
        if(array[i] !== array[i+1]) {
          result.push(array[i]);
        }
      }
      return result;
 }

//  Method 7:  Compare the current element with each item after the array , If there are equality items, discard the current element , If there is no equality, it will be added to the new array 
function arrRemoval(array) {
      let result = [];
      for(let i=0;i<array.length;i++) {
        for(let j=i+1;j<array.length;j++) {
          if(array[i] == array[j]) {
            i++;
          }
        }
        result.push(array[i]);
      }
      return result;
}

 

原网站

版权声明
本文为[wen_ Wen Wen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206252102466311.html