Filtering duplicate values is a common function in arrays. here we can use traversal to perform operations. I hope this article will help you.
Example 1
The Code is as follows: |
Copy code |
<Script type = "text/javascript"> Array. prototype. del = function (){ Var a = {}, c = [], l = this. length; For (var I = 0; I <l; I ++ ){ Var B = this [I]; Var d = (typeof B) + B; If (a [d] === undefined ){ C. push (B ); A [d] = 1; } } Return c; } Var myArr = ['text', 'text', '5', '2', '2', '3', '4', '5 ', '5']; Document. write (myArr. del ());
</Script> |
Example 2
The Code is as follows: |
Copy code |
<Script type = "text/javascript" language = "javascript"> Function filterArray (array ){ Var key = 0; // initialize the key value Var arr = new Array (); // declare an Array Var num = array. length; // array length For (var I = 0; I <num; I ++) {// cross comparison of Arrays // When comparing repeated values, to avoid comparing yourself, you need to + 1 on the current basis, such as array [0], array [1], if array [0] is compared, array [1] instead of array [0], For (var j = I + 1; j <num; j ++ ){ If (array [I] = array [j]) {// compare the cross array Array [I] = null; // unset if equal Break; // and jump out } } } For (var I = 0; I <num; I ++) {// traverse the array If (array [I]) {// determines whether it is null Arr [key ++] = array [I]; // assign the filtered array to the new array arr } } Return arr; } </Script> |
Call Method
The Code is as follows: |
Copy code |
<Script type = "text/javascript" language = "javascript"> Var arrDemo = new Array (, 11 ); Console. log (filterArray (arrDemo )); Alert (filterArray (arrDemo )); </Script> |