The input

var arr=[1.2.3.2.3.1.6.4.5.1];
Copy the code

The output

var arr=[1.2.3.6.4.5];
Copy the code

Method 1 (map/for/forEach + indexOf)

Iterate over the input, if the number is not in the output array, and put it in the output array.

function unique(arr){
	var res=[];
	arr.map(item= >{
		if(res.indexOf(item)===- 1){ res.push(item); }});return res;
}; 
var arr=[1.2.3.2.3.1.6.4.5.1];
unique(arr);/ /,2,3,6,4,5 [1]
Copy the code

Method 2 (includes)

Includes checks whether an array has a value, similar to indexOf

function unique(arr){
	if(!Array.isArray(arr)){return false}
	var res=[];
	arr.forEach(item= >{
		if(!res.includes(item)){
			res.push(item);
		}
	})
	return res;
};
var arr=[1.2.3.2.3.1.6.4.5.1];
unique(arr); // [1, 2, 3, 6, 4, 5]
Copy the code

Method three (… Or array. from with new Set)

Take advantage of the properties of Set. Convert an array to a Set, complete the de-duplication, and then convert it to an array

Set: If you pass an iterable, all of its elements are added to the new Set without repeating. If this parameter is not specified or its value is null, the new Set is null

function unique(arr){
	return Array.from(new Set(arr));
};
function unique(arr){
	return [...new Set(arr)];
};
var arr=[1.2.3.2.3.1.6.4.5.1];
unique(arr); // [1, 2, 3, 6, 4, 5]
Copy the code

Methods four

Methods five

Method 6 (Reduce + includes)

function unique(arr){
    return arr.reduce((prev,cur) = > prev.includes(cur) ? prev : [...prev,cur],[]);
};
var arr=[1.2.3.2.3.1.6.4.5.1];
unique(arr); // [1, 2, 3, 6, 4, 5]
Copy the code

conclusion

  • The includes implementation should be based on indexOf.
  • The most intuitive way to do this is to return an array that’s not there.