Three kinds of methods
Using IndexOf to judge new arrays
Underscore.js is actually used in a similar indexof
Incoming array
function unique1 (arr) {
var tmparr = [];
for (var i=0 i<arr.length; i++) {
//If the current array has already been saved in the temporary array, skip,
//or push the current item to the temporary array if
(tmparr.indexof (Arr[i]) = = = 1) {
Tmparr.push (arr[i])
;
}
return tmparr;
}
Using indexof to judge old arrays
function Unique2 (arr) {
var tmparr = [];//result array for
(Var i=0; i<arr.length; i++) {
// If the first occurrence of the current array in the current array is not I,
//It means that item I is duplicated and ignored. Otherwise deposit the result array
if (Arr.indexof (arr[i]) = = i) {
tmparr.push (arr[i]);
}
return tmparr;
}
Use hash to find
This uses the JS object's implementation is the hash table characteristic
function Unique3 (arr) {
var tmparr = [], hash = {};//hash to hash table for
(var i=0;i<arr.length;i++) {
if (!hash[ Arr[i]] {//If there is no current item
hash[arr[i] = true;//in hash table
Tmparr.push (arr[i));//Save 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;
}
Using Set
Set and map are new data structures in ES6
Set can directly store a set of keys that are not duplicated, and this key can also be objects, strings, etc.
Create set
var s = new Set ([1, 2, 3,]);
S Set {1, 2, 3}
New elements
>>> 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}
Traversing elements
Map and set cannot use subscript
The ES6 Standard introduces a new type of iterable, 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 directly using the Iterable built-in foreach method
The Foreach method is introduced by the ES5.1 standard.
var s = new Set ([' A ', ' B ', ' C ']);
S.foreach (function (element, set) {
alert (element);
});
The above mentioned is the entire content of this article, I hope you can enjoy.