Array de-weight from "complex" to "simple"

Source: Internet
Author: User
Tags new set repetition hasownproperty

Objective

As JavaScript provides more syntax, there are more and more ways to re-weigh arrays. Now from the most primitive way to the most concise way, step by step to analyze.

Double loop

The array de-weight, is not the comparison of array elements, to remove the repetition. The most primitive way is not the double cycle of comparison processing.

123456789101112131415161718192021 Test data Var test = [1,2,2,10, ' 1 ', ' A ', ' a ', ' B ', ' @ ', ' @ ']; console.log (unique1 (test));   //[1,2,10, ' 1 ', ' A ', ' B ', ' @ '] function unique1 (target) {   //double loop to compare array elements for de-weight   var res = [];      //holds data   for (var i = 0; i<target.length; i++) {      for (var j = 0,reslen = Res.length; J < Reslen; J + +) {     & Nbsp;if (target[i] = = = Res[j]) {  //If you have the same data, Break        break ;       }    }     if (j = = = ResLen) {    //res does not have the same data, then store       res.push (Target[i])      }  }  return res;}

Creates an array of res to hold the returned result; the outer loop iterates through each of the array elements in target, and the inner loop compares the element in target with each value in the Res array, and if it is not the same, it is stored in the Res. The loop is finished, returning the array after the redo. This primitive approach has good compatibility

IndexOf optimization of inner-layer loops

Use indexof to optimize the inner loop in this chestnut. The IndexOf () method returns the first index in the array where a given element can be found, or 1 if it does not exist.

123456789101112 var unique4_1 = (target) = [... new set (target)]; console.log (unique2 (test));   //[ 1,2,10, ' 1 ', ' A ', ' B ', ' @ '] function unique2 (target) {   //indexof simplifies inner loop   var  res = [];      //holds data   for (var i = 0; i<target.length; i++) {& Nbsp;   if (Res.indexof (target[i]) < 0)   //If the element does not exist in res, return -1     Res.push (Target[i])   }  return res;}

Using the IndexOf method, there is no need for an inner loop, and there are other ways to optimize the inner loop.

Object key-value pairs optimize inner-layer loops

object's keys are duplicated, and this feature can be used to judge the repetition of the elements

    //test Data varTest = [1,2,2,Ten,'1','a','a','b','@','@']; Console.log (UNIQUE3 (test)); //[1,2,10, ' A ', ' B ', ' @ '] because the object key is a string so this way would think that 1 and ' 1 ' are the same function Unique3 (target) {//How object key values are varobj = {}; varres =Target.filter (function (value,index) {returnObj.hasownproperty (value)?false: (Obj[value] =true); }) returnRes; }

NOTE: Because the keys of the object are characters, it is not possible to distinguish between 1 and ' 1 ', so you need to make a change, and then add the type judgment. Do not understand the type of judgment can refer to the previous post: http://www.cnblogs.com/shapeY/p/7600460.html

function Unique4 (target) {//How object key values are varobj = {}; varres =Target.filter (function (value,index) {returnObj.hasownproperty (typeofValue + value)?false: (obj[typeofValue + value] =true); }) returnRes; }

With the type judgment, 1 corresponds to Number1, ' 1 ' corresponds to String1, and can be separated by normal area.

Filter to optimize the outer loop

Use filter in this chestnut to optimize the outer loop. The filter () method creates a new array that contains all the elements of the test implemented by the provided function.

12345678910 var test = [1,2,2,10, ' 1 ', ' A ', ' a ', ' B ', ' @ ', ' @ ']; console.log (unique5 (test));   //[1,2,10, ' 1 ', ' A ', ' B ', ' @ '] function unique5 (target) {   //filter simplifies the outer loop   var res = Target.filter (function (Value,index,array) {    return target.indexof (value) = = = Index     //returns TRUE&NBSP;&NBSP for the first time;})   return res}

Filtering directly on target, returns True if the element first appears, or false, so that each element in the newly created array will only appear once for the purpose of de-weight. At this point we no longer use the For loop, and the amount of code is much reduced.

Set de-weight

ES6 provides a new Set of data structures. It is similar to an array, but the values of the members are unique and have no duplicate values. This feature is used to get the array to be heavy and convenient.

1234567 var test = [1,2,2,10, ' 1 ', ' A ', ' a ', ' B ', ' @ ', ' @ '];  Console.log (Unique6 (test)); [1,2,10, ' 1 ', ' A ', ' B ', ' @ '] function Unique6 (target) {//es6--set return [... new set (target)]}

’...’ is an extension operator in ES6, where the function is to expand the set into a comma-separated sequence of arguments, and it is very simple to implement an array de-weight. Children who are unfamiliar with the ES6 Grammar are aware of their own first. If you use the arrow function again, it is really a sentence to be done, as follows:

    //test Data varTest = [1,2,2,Ten,'1','a','a','b','@','@']; varUnique6_1 = (target) = = [...NewSet (target)];//Crisp Console.log (Unique6_1 (test));//[1,2,10, ' 1 ', ' A ', ' B ', ' @ ']
Conclusion

At this point, a line from the more than 10-line code of the double loop to the last set+ arrow function is done. From ' Complex ' to ' Jane ' have realized the weight of the array, the code is reduced behind the application of the JavaScript method. In fact, the core ideas have not changed, the means of implementation has changed.

Array de-weight from "complex" to "simple"

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.