JS joins multiple arrays and removes duplicate elements:
In practice, it may be necessary to merge multiple arrays into an array and remove duplicate elements from the array.
The code example is as follows:
var a=["Antzone", "Ant Tribe", "South District"], b=["New sharp Technology", "Ant Tribe", "Hard Struggle",C=[2, "New sharp Technology", "JS Tutorial"], _a =A.concat (b). Concat (c), _hash={}, _new=for (var i=_a.length; i--;) { if(! _hash[_a[i]] { _hash[_a[i]]=1; _new.push (_a[i]); }; }; Console.log (_new)
The above code implements our requirements, you can connect three arrays, and delete the duplicate elements, the following describes the implementation of this effect.
I. Principle of implementation:
It is very simple to use the CONCAT function to concatenate several arrays together before deleting the duplicate elements in the new array, and the method of removing the repeating elements is very straightforward, that is, the element in the array is the property of the object, and if there is no such attribute in the object, the value is stored in the new array, if not, You can then repeat this value as a property of the object, and see the code comment.
two. Code comments:
1.var a=["Antzone", "Ant Tribe", "South District"], declare an array using the direct amount method.
2._a=a.concat (b). Concat (c), concatenate the array into an array.
3._hash={}, declares an object that takes the elements of an array as attributes.
4._new=[], declares a new array that stores the elements after the delete is duplicated.
5.for (var i=_a.length;i--;) {}, loop statement, this is equivalent to the for (Var i=_a.length;i>0i--;).
6.if (!_hash[_a]) to determine whether the object contains all of this property.
7._hash[_a]=1, if not, add this property and set the property value to 1, which is set to 1 here is nothing special, though one can.
8._new.push (_a) to add this element to the new array.
three. Related reading:
The 1.contact () function can refer to the concat () method section of the JavaScript array object .
The 2.push () function can refer to the section of the push () method of the JavaScript array object .
The original address is: http://www.softwhy.com/forum.php?mod=viewthread&tid=11491
For more information, refer to: http://www.softwhy.com/javascript/
JS joins multiple arrays and removes duplicate elements