JavaScript arrays go from slow to fast _javascript tips from complex to simple (optimized)

Source: Internet
Author: User
Tags data structures map data structure new set javascript array

In the array operation will often encounter the problem of removing duplicates, the following is a brief introduction to the method of the array to weight.

IndexOf to Heavy

Array.prototype.unique1 = function () {
var arr = [];
for (var i = 0; i < this.length i++) {
var item = this[i];
if (arr.indexof (item) = = 1) {
Arr.push (item);
}
}
return arr;
}
[1,2,3, ' 4 ', 3,4,3,1, ' n ', 2].unique1 (); [1, 2, 3, "4", 4, "34"]

However, under Ie6-8, the IndexOf method of the array does not exist (although this is a bit of an old topic for O (∩_∩) o~), the programmer will write a indexOf method:

var indexOf = [].indexof? function (arr, item) {return
arr.indexof (item);
}:
function indexOf (arr, item) {for
(var i = 0; i < a Rr.length; i++) {
if (arr[i] = = Item) {return
i;
}
}
return-1;
}
Array.prototype.unique2 = function () {
var arr = [];
for (var i = 0; i < this.length i++) {
var item = this[i];
if (arr.indexof (item) = = 1) {
Arr.push (item);
}
}
return arr;
}
[1,2,3, ' 4 ', 3,4,3,1, ' n ', 2].unique2 (); [1, 2, 3, "4", 4, "34"]

IndexOf can also use such a way to weight the idea:

Array.prototype.unique3 = function () {
var arr = [This[0]]; 
for (var i = 1; i < this.length i++) 
{
if (This.indexof (this[i)) = i) {
arr.push (this[i]); 
return
arr;
}
[1,2,3, ' 4 ', 3,4,3,1, ' n ', 2].unique3 (); [1, 2, 3, "4", 4, "34"]

Hash Go heavy

The above indexof correctness is no problem, but performance, double cycle will reduce performance. Then we'll use hash.

Array.prototype.unique4 = function () {
var arr = [];
var hash = {};
for (var i = 0; i < this.length i++) {
var item = this[i];
var key = typeof (item) + Item
if (Hash[key]!== 1) {
Arr.push (item);
Hash[key] = 1;
}} 
return arr;
}
[1,2,3, ' 4 ', 3,4,3,1, ' n ', 2].unique4 (); [1, 2, 3, "4", 4, "34"]

The core is to build a hash object to replace IndexOf. Space to change time. Note that in JavaScript, the key value of an object can only be a string (of course, ES6 provides a map data structure.) It is similar to an object and a collection of key-value pairs, but the range of keys is not limited to strings, and values of various types, including objects, can be treated as keys. That is, the object structure provides a "string-value" counterpart, and the map structure provides a "value-value" counterpart, and is a more complete hash structure now. , so you need the var key = typeof (item) + Item to differentiate between numeric 1 and string ' 1 '.

So if you want ' 4 ' and 4 are considered the same words (other methods are the same)

Array.prototype.unique5 = function () {
var arr=[];
var hash={};
for (Var i=0,len=this.length;i<len;i++) {
if (!hash[this[i]]) { 
arr.push (this[i]);
Hash[this[i]]=true
}
}
return arr;
}
[1,2,3, ' 4 ', 3,4,3,1, ' n ', 2].unique5 (); [1, 2, 3, "4", "34"]

Sort after go heavy

Array.prototype.unique6 = function () {
this.sort ();
var arr = [This[0]];
for (var i = 1; i < this.length i++) {
if (This[i]!== arr[arr.length-1]) {
Arr.push (this[i));
}
return arr;
}
[1,2,3, ' 4 ', 3,4,3,1, ' n ', 2].unique6 (); [1, 2, 3, "34", "4", 4]

First the array to sort, and then compare the adjacent two values, sorted by the JS native sort method, so very fast. The flaw of this method is only one point, when comparing characters, they are sorted in the order of character encoding. So you'll see 10 rows in front of 2. But it does not affect the weight of the trip. The problem with sort, however, is that the sort method accepts a parameter, which is a method:

function Compare (value1,value2) {
if (value1 < value2) {
return-1;
} else if (value1 > value2) {
   return 1;
} else {return
0;
}
}
[1,2,5,2,10,3,20].sort (Compare); [1, 2, 2, 3, 5, 10, 20]

Set Go heavy

ES6 provides a new set of data structures. It is similar to an array, but the values of the members are unique, with no duplicate values. The browser is now fully supported and server node is already supported.

Array.prototype.unique7 = function () {return
Array.from (The new Set (this));
}
[1,2,3, ' 4 ', 3,4,3,1, ' n ', 2].unique7 (); [1, 2, 3, "4", 4, "34"]

Method Library

Recommend a method library Underscore.js, is very popular in node or browser JS.

Const _ = require (' underscore ');
_.uniq ([1, 2, 1, 3, 1, 4]); [1, 2, 3, 4]

Test time

All of the above methods can be used in a simple way to test the time spent, and then do a better job of each method:

Console.time ("test");
[1,2,3, ' 4 ', 3,4,3,1, ' n ', 2].unique7 ();
Console.timeend ("test");
==> Vm314:3 test:0.378ms

To make the data larger, you randomly create 1 million numbers:

var arr = [];
var num = 0;
for (var i = 0; i < 1000000 i++) {
num = Math.floor (math.random () *100);
Arr.push (num);
}
Console.time ("test");
Arr.unique7 ();
Console.timeend ("test");

The above is a small set to introduce the JavaScript array to the heavy from slow to fast from the complex to Jane, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.