Js array deduplication method summary, js array Summary
Three methods
Use indexOf to determine the new array
Similar indexOf is actually used in underscore. js.
// Input the Array function unique1 (arr) {var tmpArr = []; for (var I = 0; I <arr. length; I ++) {// if the I of the current array has been saved in a temporary array, skip this step. // otherwise, push the current item to the temporary array if (tmpArr. indexOf (arr [I]) =-1) {tmpArr. push (arr [I]);} return tmpArr ;}
Use indexOf to determine the old Array
Function unique2 (arr) {var tmpArr = []; // result array for (var I = 0; I <arr. length; I ++) {// if the position where the I entry of the current array appears for the first time in the current array is not I, // It indicates that the I entry is repeated, ignore. Otherwise, the stored result array if (arr. indexOf (arr [I]) = I) {tmpArr. push (arr [I]) ;}} return tmpArr ;}
Search by hash
The implementation of JS objects is the feature of hash tables.
Function unique3 (arr) {var tmpArr = [], hash = {}; // hash is the hash table for (var I = 0; I <arr. length; I ++) {if (! Hash [arr [I]) {// If the hash table does not have the current item hash [arr [I] = true; // save it to the hash table tmpArr. push (arr [I]); // save to a temporary array} return tmpArr ;}
Array Extension
Array. prototype. unique1 = function () {var tmpArr = []; for (var I = 0; I <this. length; I ++) {if (tmpArr. indexOf (this [I]) =-1) {tmpArr. push (this [I]);} return tmpArr;} Array. prototype. unique2 = function () {var tmpArr = []; // result array for (var I = 0; I <this. length; I ++) {if (this. indexOf (this [I]) = I) {tmpArr. push (this [I]);} return tmpArr;} Array. prototype. unique3 = function () {var tmpArr = [] , Hash = {}; for (var I = 0; I <this. length; I ++) {if (! Hash [this [I]) {hash [this [I] = true; tmpArr. push (this [I]) ;}} return tmpArr ;}
Use Set
Set and Map are new data structures in ES6.
Set can directly store a Set of keys that are not repeated. This key can also be an object or a string.
Create a set
var s = new Set([1, 2, 3,]);s; // Set {1, 2, 3}
Add Element
>>> S. add (4) >>> s {1, 2, 3, 4 }>>> s. add (4) >>> s {1, 2, 3, 4} // duplicate elements are not added
Delete Element
s; // Set {1, 2, 3, 4}s.delete(3);s; // Set {1, 2, 4}
Traversal Element
Map and Set cannot use subscript
The ES6 standard introduces the new iterable type. Array, Map, and Set all belong to the iterable type.
Var s = new Set (['A', 'B', 'C']); for (var x of s) {// traverse Set alert (x );}
Or you can directly use the iterable built-in forEach method.
The forEach method is introduced in the ES5.1 standard.
var s = new Set(['A', 'B', 'C']);s.forEach(function (element, set) { alert(element);});
The above is all the content of this article. I hope you will like it.