What are the 5 methods to remove duplicates from arrays?
5 ways to remove duplicates from arrays:
Method 1:
Double for loop Deduplication
Principle: If two pairs are compared, delete the second one
For example: 1 1 1 3 2 1 2 4
Let the first 1 be arr [0] Compare with the following ones one by one. If the following value is equal to arr[0], delete the following value
The result after the first end is 1 3 2 2 4, delete all the following 1
Similarly, the second and third times will delete the same elements as yourself
function noRepeat1(arr){ // 第一层for用来控制循环的次数 for(var i=0; i Copy after login
Method 2:
Single-layer for loop
Principle Similar to method one
function norepeat(arr){ arr.sort(); //先排序让大概相同的在一个位置,这里为什么说是大概相同 是因为sort排序是把元素当字符串排序的 它和可能排成 1 1 10 11 2 20 3 ... 不是我们想要的从小到大 for(var i = 0; i < arr.length-1;i++){ //还是两两比较 一样删除后面的 if(arr[i]==arr[i+1]){ arr.splice(i,1); //i-- 和j--同理 i--; } } return arr; }
Method three:
Principle: Use an empty array to store the first appearing element
Use the indexOf attribute indexOf to return a specified The position where the character appears in the string. If not, -1 will be returned.
So we can make good use of this property. When -1 is returned, it will be stored in the array.
function noRepeat2(arr){ var newArr = []; for(var i = 0; i < arr.length; i++){ if(newArr.indexOf(arr[i]) == -1){ newArr.push(arr[i]); } } return newArr; }
Method 4:
Principle: Use the idea of the object. If there is no such attribute in the object, undefined will be returned.
Use this principle to put it into the array when the returned value is undefined. When assigning a value to this attribute
function norepeat3(arr) { var obj = {}; var newArr = []; for(var i = 0; i < arr.length; i++) { if(obj[arr[i]] == undefined) { newArr.push(arr[i]); obj[arr[i]] = 1; } } return newArr; }
Method 5:
Principle: If the loop comparison is equal, the value of the following elements will be 0, and finally deleted to 0 during output The premise is that there cannot be 0 in your data, but everything can be flexible. You can set any value to replace this 0. This method was what I thought of implementing at the time, so it was not well optimized.
var newArr = []; //控制外循环 for(var i=0; i Copy after login
Recommended tutorial: "PHP Video Tutorial"
The above is the detailed content of What are the 5 methods of deduplicating arrays?. For more information, please follow other related articles on the PHP Chinese website!