1. Array deduplication;
The Array type does not provide a method to remove duplicates. If you want to remove duplicate elements from the array, you have to find a way yourself:
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 transfer the array elements to another array one by one. During the transfer process, check whether the element is duplicated, and if so, discard it directly. As can be seen from nested loops, this method is extremely inefficient. We can use a hashtable structure to record existing elements, so that we can avoid inner loops. It just so happens that implementing hashtable in Javascript is extremely simple. 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 recommended methods for deduplicating JavaScript arrays are all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.