Home >Web Front-end >JS Tutorial >How to implement JS array deduplication algorithm
This time I will show you how to implement the JS array deduplication algorithm and what are the precautions for implementing the JS array deduplication algorithm. The following 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<arr.length>Test result: <p style="text-align: left;"></p> <blockquote style="text-align: left;"> unique1(arr): ["1", 3, 1, 4, 5, "2", Object { name="li", age=20}, 2, Object { name="li", age=20}, ""]<p style="text-align: left;"></p> </blockquote>bug Unable to distinguish objects<p style="text-align: left;"></p> <p style="text-align: left;">Method 2: Use <strong>Object object<a href="http://www.php.cn/wiki/48.html" target="_blank"> in </a>JavaScript<a href="http://www.php.cn/code/8123.html" target="_blank"> as Ha Greek table</a></strong></p> <pre class="brush:php;toolbar:false">function unique2(arr){ var temp=[]; var hash={}; for(var i=0; i<arr.length>Test result:<p style="text-align: left;"></p> <blockquote style="text-align: left;">unique2(arr): ["1", 3, 4, 5, "2", Object { name="li ", age=20}, ""]<p style="text-align: left;"></p> </blockquote>bug: Unable to distinguish: 1 and "1"<p style="text-align: left;"></p>Modification<p style="text-align: left;"></p> <pre class="brush:php;toolbar:false">function unique2(arr){ var temp=[]; var hash={}; for(var i=0; i<arr.length>Test result:<p style="text-align: left;"></p> <blockquote style="text-align: left;">unique2(arr): ["1", 3, 1, 4, 5, "2", Object { name="li", age=20}, 2, ""]<p style="text-align: left;"></p> </blockquote> <p style="text-align: left;">Method 3: First use sort to sort the <strong> array<a href="http://www.php.cn/code/54.html" target="_blank">, 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</a></strong></p> <pre class="brush:php;toolbar:false">function unique3(arr){ arr.sort(function(a,b){ return a-b; }); var temp = []; for(var i=0;i<arr.length> 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! <p></p>Recommended reading: <p></p> <p>How to operate Angular to implement data requests<a href="http://www.php.cn/js-tutorial-399386.html" target="_blank"></a><br></p> <p>How to operate node and use async to control concurrency<a href="http://www.php.cn/js-tutorial-399385.html" target="_blank"></a><br></p></arr.length>
The above is the detailed content of How to implement JS array deduplication algorithm. For more information, please follow other related articles on the PHP Chinese website!