Recommended two methods for removing duplicated JavaScript Arrays: javascript Array
1. array deduplication;
The Array type does not provide the deduplication method. If you want to remove the repeated elements of the Array, you have to find a solution:
Method 1: Use the indexOf method;
var aa=[1,3,5,4,3,3,1,4]function arr(arr) { var result=[] for(var i=0; i<arr.length; i++){ if(result.indexOf(arr[i])==-1){ result.push(arr[i]) } } console.log(result)} arr(aa)
Method 2:
function unique(arr) { var result = [], isRepeated; for (var i = 0, len = arr.length; i < len; i++) { isRepeated = false; for (var j = 0, len = result.length; j < len; j++) { if (arr[i] == result[j]) { isRepeated = true; break; } } if (!isRepeated) { result.push(arr[i]); } } return result;}
Method 2,The general idea is to move the array elements one by one to another. During the handling process, check whether there are duplicates of the elements. If so, the elements are discarded directly. From nested loops, we can see that this method is very inefficient. We can use a hashtable structure to record existing elements, so as to avoid inner loops. Exactly, implementing hashtable in Javascript is extremely simple, and the improvements are as follows:
function unique(arr) { var result = [], hash = {}; for (var i = 0, elem; (elem = arr[i]) != null; i++) { if (!hash[elem]) { result.push(elem); hash[elem] = true; } } return result;}
The above two methods of de-duplicating the JavaScript array are all the content shared by the editor. I hope to give you a reference, and I hope you can provide more support for the customer's house.