This time I will bring you JS to implement the array deduplication algorithm. What are theprecautions for JS to implement the array deduplication algorithm?. Here is a practical case, let’s take a look.
Test case:
arr = ["1",3,"1",1,4,5,1,"2",5,1,{"name ":"li","age":20},2,4,3,{"name":"li","age":20},""];
Method 1: With the help of temporary array and indexOf,The algorithm complexity is:O(n^2)
function unique1(arr){ var temp = []; for(var i=0; i Copy after login
Test result:
unique1(arr): ["1", 3, 1, 4, 5, "2", Object { name="li", age=20}, 2, Object { name="li", age=20}, ""]
bug Unable to distinguish objects
Method 2: UseObject objectinJavaScriptas Ha Greek table
function unique2(arr){ var temp=[]; var hash={}; for(var i=0; i Copy after login
Test result:
unique2(arr): ["1", 3, 4, 5, "2", Object { name="li ", age=20}, ""]
bug: Unable to distinguish: 1 and "1"
Modification
function unique2(arr){ var temp=[]; var hash={}; for(var i=0; i Copy after login
Test result:
unique2(arr): ["1", 3, 1, 4, 5, "2", Object { name="li", age=20}, 2, ""]
Method 3: First use sort to sort thearray, and then use a temporary array to store the last one of the same element. This method can only be used for pure Number type arrays
function unique3(arr){ arr.sort(function(a,b){ return a-b; }); var temp = []; for(var i=0;i Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of JS callback function usage cases
What are the precautions in actual React Navigation
The above is the detailed content of JS implements array deduplication algorithm. For more information, please follow other related articles on the PHP Chinese website!