Array de duplication (1)


An array

let arr = [1,2,2,4,null,null,'3','abc',3,5,4,1,2,2,4,null,null,'3','abc',3,5,4];
let len = arr.length;

1、 Using the uniqueness of object key value to filter array

let obj = {};
for(let i =0; i<len; ++i){
  let tmp =  arr[i];
  If (obj [TMP]! = = undefined) {// exists in the object. Remove it
  obj[tmp] = tmp;  //  Stored in object

2、 Swap element positions to replace the split method
The first method has an efficiency problem. The deletion performance of splice is not very good. After the current item is deleted, the index of each item will move forward one bit. When the amount of data is large, the performance will be affected.
New idea: if the current element is repeated, the position will be exchanged with the last element of the array. I — judge again, and length — operate the length of the array to delete the last element of the array, so as not to affect other elements in the array.

let obj = {};
for(let i =0; i<len;++i){
  let tmp =arr[i];
  if(obj[tmp] !== undefined){
     arr[i] = arr[len-1];
  obj[tmp] = tmp;

3、 Filter and indexof methods
Filter () does not detect empty arrays.
Filter () does not change the original array and is a pure function.
Returns the element where the first occurrence of item is equal to the current index

let result = arr.filet((item,index)=>{
  arr.indexOf(item) === index; //  After traversing, the first value will always be found. The index value of the first value is equal to index

4、 Filter and object.hasownproperty
Hasownproperty () method: returns a Boolean value indicating whether the object has the specified property in its own property

let obj = {};
arr.filter(item=>obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item ] = true))

5、 Sort the array once with the sort method. Then compare whether the front and rear elements are equal

function unique(arr) {
        console.log("type error ,not a function")
    arr = arr.sort();
    let result = arr[0];
    for(let i = 1; i<arr.length;++i){
        if(arr[i] !== arr[i-1]){
    return result

6、 Using the include function, the core code is to judge the include in the loop
Replace the loop and use reducer to handle it

arr.reduce((pre,cur)=>pre.includes(cur) ? pre : [...pre,cur],[])

The effect is the same.