Four common ways to deduplicate arrays

1. Double-layer for loop deduplication

Determine whether the previous element and the next element are equal, and if they are equal, delete the next element

function func(tempArr){
	for(var i=0;i<tempArr.length;i++){
		for(var j=i+1;j<tempArr.length;j++){
			if(tempArr[i]==tempArr[j]){
				tempArr.splice(j,1);
                j--;
			};
		};
	};
	return tempArr;
};
var arr = [20,3,4,45,34,43,20,45,60];
console.log(func(arr)); //(7) [20, 3, 4, 45, 34, 43, 60]

2. Sort first and then deduplicate

Sort first, then compare two adjacent elements, if they are not equal, push the previous element into the new array

function func(tempArr){
    tempArr.sort(function(a,b){//sort()方法会影响原数组的顺序
        return a-b;
    });		
    var newArr = [];
	for(var i=0;i<tempArr.length;i++){
		if(tempArr[i]!=tempArr[i+1]){
			newArr.push(arr[i]);
		};
	};
	return newArr;
};
var arr = [20,3,4,45,34,43,20,45,60];
console.log(func(arr)); //(7) [20, 3, 4, 45, 34, 43, 60]

3. Use subscripts to remove duplicates

Create a new empty array, judge that the number in the original array is the first time, then put this number into the new array

function func(tempArr){
	var newArr = [];
	for(var i=0;i<tempArr.length;i++){
		if(newArr.indexOf(tempArr[i])==-1){//需注意:IE8以下不支持indexOf()方法
			newArr.push(arr[i]);
			//等价于下面两种写法
			//newArr.splice(i,0,arr[i]);
			//newArr.splice(newArr.length,0,arr[i]);
		};
	};
	return tempArr;
};
var arr = [20,3,4,45,34,43,20,45,60];
console.log(func(arr)); //(7) [20, 3, 4, 45, 34, 43, 60]

4. Use includes to deduplicate

Create a new array, determine whether the new array contains the elements in the array to be deduplicated, if not, push the element into the new array

function func(tempArr){
	var newArr = [];
	for(var i=0;i<tempArr.length;i++){
		if(!newArr.includes(tempArr[i])){
			newArr.push(tempArr[i]);
		};
	};
	return newArr;
};
var arr = [20,3,4,45,34,43,20,45,60];
console.log(func(arr)); //(7) [20, 3, 4, 45, 34, 43, 60]

Guess you like

Origin blog.csdn.net/weixin_55992854/article/details/117371667