The problem
describe
Adds a method to remove duplicates for Array objects
Example 1
Input: [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN] output: [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']Copy the code
Array de-duplication is not difficult in itself, but one thing to be aware of is what to do if the input contains two nans.
NaN can be identified:
-
isNaN()
-
Includes () returns true if it exists
const arr = [1.true.NaN.23.'hello']
/ / includes contains
console.log(arr.includes(NaN)) //true
Copy the code
- Object.is()
console.log(Object.is(NaN.NaN)); //true
Copy the code
NaN cannot be recognized:
- indexOf()
NaN==NaN =>false, so indexof cannot determine the indexof NaN
Here’s an idea:
We can filter data based on whether arr.indexof(item) is equal to the indexof the current item, since indexof only returns the indexof the element that first appears in the array. For data other than NaN, this can be determined by determining whether the index returned is the same as the indexof the current element.
The issues to watch out for are:
The array contains NaN, NaN==NaN =>false, so indexof cannot determine the indexof NaN.
Methods to determine NaN:
- Number. IsNaN (item) check whether the value is of type Number and then NaN.
- Flag == 0 to determine if it is a duplicate NaN. The first NaN is already in the new array and flag++ is executed. So the NaN that appears later does not satisfy flag == 0 and will not 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 the code