Home > Article > Web Front-end > Summary of three common methods to remove duplicates from js arrays_javascript skills
The first is the more conventional method
Things:
1. Construct a new array to store the results
2. Each time in the for loop, one element is taken out from the original array, and this element is used to compare the loop with the result array
3. If the element does not exist in the result array, store it in the result array
Things:
1. Sort the original array first
2. Check whether the i-th element in the original array is the same as the last element in the result array. Because it has been sorted, duplicate elements will be in adjacent positions
3. If they are not the same, store the element in the result array
The third method (recommended)
Things:
1. Create a new array to store the results
2. Create an empty object
3. During the for loop, each time an element is taken out and compared with the object. If the element is not repeated, it is stored in the result array. At the same time, the content of this element is used as an attribute of the object and assigned a value of 1. , stored in the object created in step 2.
Explanation: As for how to compare, it is to take out one element from the original array each time, and then access this attribute in the object. If the value can be accessed, it means it is repeated.
var arr = [112,112,34,'Hello',112,112,34,'Hello','str','str1'];
alert(arr.unique3());