Mode 1:
<script> function getsome(){ let result=[]; let a=[1,2,3,2,3,4,2,1,5]; for(let i=0;i<a.length;i++){ for(let j=i+1;j<a.length;j++){ if(a[i]==a[j]){ let num=a.splice(j,1); result.push(num); j--; } } } console.log(a); return result; } var jieguo=getsome(); console.log("Array of repeating elements"+jieguo+"\n"+"The length of the array"+jieguo.length); </script>
Operation result:
[1, 2, 3, 4, 5]
Array of repeating elements 1,2,2,3
Length of the array 4
Add: this method finally gets the array composed of repeated elements, and removes the repeated elements from the original array, but its time complexity is o(n^2).
Mode two:
<script> function getResult(){ let a=[3,2,4,2,1,45,4,6]; a.sort(function(num1,num2){ return num1-num2; }); //Console.log (a); the sort method changes the original array order let result=[a[0]]; // console.log(result); for(let i=1;i<a.length;i++){ if(a[i]!==result[result.length-1]){ result.push(a[i]); } } return result; } var res=getResult(); console.log(res); </script>
Operation result:
[1, 2, 3, 4, 6, 45]
Conclusion: compared with the first time, the time complexity of this method is obviously reduced, but there are still great limitations.
First of all, it sorts the array, then applies for a space to store the first element value of the sorted array, then iterates over the remaining values, and adds the ones that are not in the array. However, it changes the original order of the array.
Method 3:
<script> function getResult(){ let a=[2,2,3,4,5,6,2,3]; let result=[]; for(let i=0;i<a.length;i++){ if(result.indexOf(a[i])===-1){ result.push(a[i]); } } return result; } var res=getResult(); console.log(res); </script>
Operation result:
[2, 3, 4, 5, 6]
Summary: this method is much better than the previous one, it does not change the order of the array. First, it is a top empty array, and then it traverses the original array A. as long as there is nothing in the result array, it will be added to the result array. The final result array is the array after de duplication. (indexOf() method of array is used)
To be continued