This article provides a summary of three methods and examples of deduplication of javascript arrays, which are very simple and practical. For more information, see.
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; IUse indexOf to determine the old Array
Function unique2 (arr) {var tmpArr = []; // result array for (var I = 0; ISearch 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; IArray 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.