# Array de duplication problem solution - Nan recognition problem

2021-08-27 15:16:30

# problem

## describe

by Array Object to add a method to remove duplicate items

## Example 1

`````` Input : [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
Output : [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']
Copy code ``````

Array de duplication itself is not difficult , One of the problems that needs attention is : If the input contains two NaN How to deal with .

# Can identify NaN:

• isNaN()

• includes() If there is a return true

``````    const arr = [1,true,NaN,23,'hello']

// includes  contain
console.log(arr.includes(NaN))  //true
Copy code ``````
• Object.is()
``````console.log(Object.is(NaN,NaN)); //true
Copy code ``````

# Can't identify NaN:

• indexOf()

NaN==NaN =>false, therefore indexof It's impossible to judge NaN The subscript of

# Here is an idea :

We can use arr.indexof(item) Whether it is equal to the subscript of the current item to filter the data , because indexof Only the subscript of the first element in the array will be returned , For addition NaN For other data , You can judge whether the returned subscript is the same as that of the current element .

The problem that needs attention is :

The array contains NaN, NaN==NaN =>false, therefore indexof It's impossible to judge NaN The subscript of .

Judge NaN Methods :

• use Number.isNaN(item) First judge whether the value is number type , Then judge whether it is NaN;
• Advance declaration flag=0, By judgment flag Is it 0 To determine whether it is repeated NaN. ( Because the judgment condition is flag == 0 when , So for the first time Nan Has been saved to a new array , And executed flag++, So what comes back later NaN No longer satisfied flag == 0 The condition of the , So it won't be stored in the new array )
``````Array.prototype.uniq = function () {
var arr = this;
var newarr = [];
var flag = 0;

for(var i=0;i<arr.length;i++){
if(Number.isNaN(arr[i]) && flag == 0){
newarr.push(arr[i]);
flag++;
}
else if(arr.indexOf(arr[i]) == i){
newarr.push(arr[i]);
}
}
return newarr;
}
Copy code ``````