当前位置:网站首页>Several methods of array de duplication in JS

Several methods of array de duplication in JS

2022-06-22 07:00:00 webchang

Code demonstration :

let arr = [1,1,'true','true',15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 'a', 'a'];

//  Method 1, It can be done to NaN Deduplication , because  Set  When we add value, we think that NaN Equal to itself 
function f1(arr) {
    
  // return Array.from(new Set(arr));
  return [...new Set(arr)];
}
console.log(' Method 1:',f1(arr));

//  Method 2, You can't be right NaN Deduplication (indexOf Method does not recognize the NaN member )
function f2(arr) {
    
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    
    if (result.indexOf(arr[i]) === -1) {
    
      result.push(arr[i]);
    }
  }
  return result;
}
console.log(' Method 2:',f2(arr));

//  Method 3, Use ES6 Of findIndex Method , Can combine Object.is() Method pair NaN Deduplication 
// Object.is() The method is that NaN Equal to itself 
function f3(arr) {
    
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    
    if (result.findIndex(value => Object.is(arr[i],value)) === -1) {
    
      result.push(arr[i]);
    }
  }

  return result;
}
console.log(' Method 3:',f3(arr));

//  Method 4: It can be done to NaN Deduplication 
//  Array of includes() The method is that NaN Equal to itself 
function f4(arr) {
    
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    
    if (!result.includes(arr[i])) {
    
      result.push(arr[i]);
    }
  }
  return result;
}
console.log(' Method 4:',f4(arr));

//  Method 5: This method will NaN Jump over , The final result will not include NaN
// indexOf The strict equality operator is used internally (===) Judge , This will lead to the right NaN Miscarriage of Justice .
function f5(arr) {
    
  return arr.filter((value,index) => {
    
    return arr.indexOf(value) === index;
  });
}
console.log(' Method 5:',f5(arr));

The above methods are similar , The following pair involves NaN Make a summary of the contents of :

NaN == NaN // false
NaN === NaN // false

// indexOf Method does not recognize the NaN member 
[NaN].indexOf(NaN) // -1

//  towards  Set  When a value is added to a data structure, it is considered that NaN Equal to itself 
let set = new Set();
set.add(NaN);
set.add(NaN);
console.log(set); // Set {NaN}

// Object.is() The method is that NaN be equal to NaN
Object.is(NaN, NaN) // true
+0 === -0 //true
Object.is(+0, -0) // false

// ES2016 New array instance method in :includes() The method is that NaN Equal to itself 
[1, 2, NaN].includes(NaN) // true

Front end learning exchange QQ Group , The atmosphere of learning and discussion in the group is very good , There are a lot of big people , Looking forward to your joining :862748629 Click to add

原网站

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