Two kinds of commonly used JavaScript array method and code _javascript technique

Source: Internet
Author: User
Tags javascript array

The first is a more conventional approach.
Ideas:
1. Build a new array to store the results
In the 2.for loop, every time you take an element out of the original array, you use IndexOf to find out whether the element is in the new array.
3. If not, save in the result array

Copy Code code as follows:

Array.prototype.unique1 = function () {
var res = [];
for (var i = 0; i < this.length; i++) {
if (Res.indexof (this[i]) = = 1) {
Res.push (This[i]);
}
}
return res;
}
var arr = [1, ' A ', ' a ', ' B ', ' d ', ' e ', ' e ', 1, 0]
Alert (arr.unique1 ())

This foundation can be slightly optimized, but the principle is not changed, the effect is not obvious
Copy Code code as follows:

Array.prototype.unique1 = function () {
var res = [this[0]];//directly to the first element in the original array into the new array being built
for (var i = 1; i < this.length i++) {//loop starts with the second element
if (Res.indexof (this[i]) = = 1) {
Res.push (This[i]);
}
}
return res;
}
var arr = [1, ' A ', ' a ', ' B ', ' d ', ' e ', ' e ', 1, 0]
Alert (arr.unique1 ())

the second method is more efficient than the above method
Ideas:
1. Sort the original array first
2. Check that the first element in the original array is the same as the last element in the result array, because it is already sorted, so the repeating element is in the adjacent position
3. If it is not the same, the element is stored in the result array
Copy Code code as follows:

Array.prototype.unique2 = function () {
This.sort (); Sort first
var res = [This[0]];
for (var i = 1; i < this.length; i++) {
if (This[i]!== res[res.length-1]) {
Res.push (This[i]);
}
}
return res;
}
var arr = [1, ' A ', ' a ', ' B ', ' d ', ' e ', ' e ', 1, 0]
Alert (Arr.unique2 ())

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.