In daily development, we may encounter the removal of repeated values in an array
Method for removing duplicate values in array:
1. Use indexOf () method to remove
Idea: Create a new array, then loop through the array to be deduplicated, then use the new array to find the value of the array to be deduplicated, if not found, use .push to add to the new array, and finally return the new array
It does n’t matter if you do n’t understand it, the code is easier to understand
function fun(arr){ let newsArr = []; for (let i = 0; i < arr.length; i++) { if(newsArr.indexOf(arr[i]) === -1){ newsArr.push(arr[i]); } } return newsArr; }
2. Use splice method to remove
Idea: This method is a bit like bubbling. The two-layer loop, the outer loop traverses the array, and the inner loop compares the values. If they are the same, use splice to remove and return the processed array
It does n’t matter if you do n’t understand it, the code is easier to understand
function fun(arr){ for (let i = 0; i < arr.length; i++) { for(let j = i+1; j < arr.length; j++){ if(arr[i]==arr[j]){ arr.splice(j,1); } } } return arr; }