An array of JavaScript learning notes to _javascript skills

Source: Internet
Author: User
Tags arrays new set

Recommended reading: Add, delete, change and check the array of JavaScript learning notes

An array summation method of JavaScript learning notes

A random sort of array of JavaScript learning notes

It often happens that the interviewer will ask JavaScript to implement array-weight issues, and recently just learned about JavaScript arrays, and took the opportunity to sort out some of the ways to weight javascript arrays.

The following arrays are collected and sorted by themselves, and if they are not, there is no point in the text.

Double cycle to heavy

This method uses two for loops for traversal. The whole idea is:

Build an empty array to store the heavy array

The For loop outside iterates over the original array, comparing each element from the array to the result array.
If the original array takes out an element that is the same as the result array element, it jumps out of the loop and, conversely, stores it in the result array

The code is as follows:

Array.prototype.unique1 = function () {
//Build a new array, storing the result
var newarray = [This[0]];
For loop, each time from the original array to take out an element
///out of the element loop and the result array contrast for
(var i = 1; i < this.length; i++) {
var repeat = false;
For (Var j=0 j < Newarray.length J + +) {
//The original array takes out elements identical to the result array element
if (this[i] = = Newarray[j]) {
repeat = true; Break
;
}
}
if (!repeat) {
//If the element is not in the resulting array, it is stored in the result array
Newarray.push (This[i]);
}
return newarray;
}

Let's say we have an array like this:

var arr = [1,2,3,4, ' A ', ' B ', 1,3,4,56,32,34,2, ' B ', ' C ', 5, ' 1 ', ' 2 '];
Arr.unique1 (); [1, 2, 3, 4, "A", "B", A, C, II, "C.", 5]

It is said that this method is more time-consuming and cost-performance. Simply do a test (the test method is written in a rather clumsy way):

function test () {
var arr = [];
for (var i = 0; i < 1000000 i++) {
Arr.push (Math.Round (Math.random (i) * 10000));
Dotest (arr, 1);
}
function Dotest (arr, n) {
var tstart = (new Date ()). GetTime ();
var re = arr.unique1 ();
var tend = (new Date ()). GetTime ();
Console.log (' Double cycle Go heavy method Use time is: ' + (Tend-tstart) + ' Ms ');
return re;
}
Test ();

In the chrome controller run the above code, test double cycle to heavy time: 11031ms.

The above method can simulate the implementation using the foreach () method and the IndexOf () method:

function unique1 () {
var newarray = [];
This.foreach (function (index) {
if (newarray.indexof (index) = = 1) {
Newarray.push (index);
}
}); return
NewArray;
}

Called by unique1.apply (arr) or Unique1.call (arr). But this method is much more efficient, the same test code above, the time spent 5423ms, almost half faster.

Sort traversal Go heavy

First, you use the sort () method to sort the original array, iterate after the sequence, and check that the first element in the array is the same as the last element in the result array. If different, the elements are placed in the result array.

Array.prototype.unique2 = function () {
//The original array sorted first
this.sort ();
Build a new array to store the result
var newarray = [];
for (var i = 1; i < this.length i++) {//check that the first element in the
original number is the same as the last element in the result
//Because it is sorted, so the repeating element will be in the adjacent position
if (This[i]!== Newarray[newarray.length-1]) {
//if different, place the element in the result array
Newarray.push (This[i]);
}
return newarray;
}

For example:

var arr = [1,2,3,4, ' A ', ' B ', 1,3,4,56,32,34,2, ' B ', ' C ', 5, ' 1 ', ' 2 '];
Arr.unique2 (); ["1", 1, 2, "2", 3,, 4, 5, MB, "a", "B", "C"]

This approach has two features:

The after-weight array is sorted, mainly because the original numbers are sorted before they go heavy.

After the weight of the array, and the number of the same number of characters can not be distinguished, such as ' 1 ' and 1

Use the same method to test the time: 1232ms.

Object key value pair method

The way to achieve this method is:

Create a JavaScript object and a new array

Use a For loop to traverse the original array, comparing each element with the key of the JavaScript object

If not, pushes the value of the element that is stored in the object into the result array and sets the value of the property name in the object to 1

The code is as follows:

Array.prototype.unique3 = function () {
//build a new array to store the result
var newarray = [];
Creates an empty object
, var object = {};
For loop, each time an element is fetched against the object/
/If the element is not duplicated, it is stored in the result number
//and the content of the element is taken as an attribute of the object and assigned to 1,
//To the object created in
step 2nd for (var i = 0; i < this.length; i++) {
//detect if the value of the element being traversed to is contained in object objects
if (!object[typeof (this[i) + this[i]) {
   //if not included, pushes the value of the element that is stored in the object into the result array
Newarray.push (This[i]);
If it is not included, the value of the property name stored in object is set to 1
object[typeof (this[i]) + this[i]] = 1;
}
return newarray;
}

Run the previous example:

var arr = [1,2,3,4, ' A ', ' B ', 1,3,4,56,32,34,2, ' B ', ' C ', 5, ' 1 ', ' 2 '];
Arr.unique3 (); [1, 2, 3, 4, "A", "B", "A", "a", "C", 5, "1", "2"]

Similarly, different keys may be mistaken for the same, for example: a[1], a["1". This method cost time: 621ms. This method takes the shortest amount of time, but it takes up a bit of memory.

In addition to the above several methods, there are several other ways to do the following:

Method four
Array.prototype.unique4 = function () {
//build a new array to store the result
var newarray = [];
Traverse the entire array
for (var i = 0; i < this.length i++) {
//traverse for duplicate values for
(j = i + 1; j < This.length; J +) {
   //If there is the same element, the self increment i variable, jump out of I loop
if (this[i] = = This[j]) {
j = ++i;
}
}
If there are no identical elements, push the elements into the result array
Newarray.push (this[i])
;
return newarray;
}

Chrome test Results

var arr = [1,2,3,4, ' A ', ' B ', 1,3,4,56,32,34,2, ' B ', ' C ', 5, ' 1 ', ' 2 '];
Arr.unique4 (); ["A", 1, 3, 4, 2, "B", "C", 5, "1", "2"]

Similarly, 1 and ' 1 ' cannot be distinguished.

Method five
Array.prototype.unique5 = function () {
//build a new array to store the result
var newarray = [];
Iterate over the entire array
for (var i = 0; i < this.length i++) {
//If the value of the current array is saved to a temporary array, skip
var index = this[i];
If the array item is not in the result array, push this value into the result array
if (newarray.indexof (index) = = 1) {
Newarray.push (index);
}
}
return newarray;
}

Chrome test Results:

var arr = [1,2,3,4, ' A ', ' B ', 1,3,4,56,32,34,2, ' B ', ' C ', 5, ' 1 ', ' 2 '];
Arr.unique6 (); [1, 2, 3, 4, "A", "B", "A", "a", "C", 5, "1", "2"]

Similarly, similar to 1 and ' 1 ' cannot be distinguished. Time taken: 14361ms.

Method six
Array.prototype.unique6 = function () {return
this.reduce (function (NewArray, index) {
if ( Newarray.indexof (Index) < 0) {
newarray.push (index);
}
return newarray;
},[]);
}

The test results are as follows:

var arr = [1,2,3,4, ' A ', ' B ', 1,3,4,56,32,34,2, ' B ', ' C ', 5, ' 1 ', ' 2 '];
Arr.unique6 (); [1, 2, 3, 4, "A", "B", "A", "a", "C", 5, "1", "2"]

Time taken: 16490ms.

Method Seven
Array.prototype.unique7 = function () {
var newarray;
NewArray = This.filter (function (Ele,i,arr) {return
arr.indexof (ele) = = i;
});
return newarray;
}

Test results:

var arr = [1,2,3,4, ' A ', ' B ', 1,3,4,56,32,34,2, ' B ', ' C ', 5, ' 1 ', ' 2 '];
Arr.unique6 (); [1, 2, 3, 4, "A", "B", "A", "a", "C", 5, "1", "2"]

Time taken: 13201ms.

Although there are many ways to do this, the following approach is a better solution than this:

Array.prototype.unique3 = function () {
//build a new array to store the result
var newarray = [];
Creates an empty object
, var object = {};
For loop, each time an element is fetched against the object/
/If the element is not duplicated, it is stored in the result number
//and the content of the element is taken as an attribute of the object and assigned to 1,
//To the object created in
step 2nd for (var i = 0; i < this.length; i++) {
//detect if the value of the element being traversed to is contained in object objects
if (!object[typeof (this[i) + this[i]) {
   //if not included, pushes the value of the element that is stored in the object into the result array
Newarray.push (This[i]);
If it is not included, the value of the property name stored in object is set to 1
object[typeof (this[i]) + this[i]] = 1;
}
return newarray;
}

But there are simpler and more optimized options for ES6, such as:

ES6
function Unique (arr) {
const seen = new Map () return
Arr.filter ((a) =>!seen.has (a) && seen . Set (A, 1))
}
//or
function unique (arr) {return
Array.from (new set (arr))
}

The above is a small set for you to introduce the JavaScript Learning notes array to heavy, I hope to help you!

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.