search
HomeWeb Front-endFront-end Q&AWhat is the sorting method of es6 array

What is the sorting method of es6 array

Apr 11, 2022 pm 06:04 PM
es6sort()arrayArray sort

The sorting method of es6 array is "sort()". The sort() method is used to sort the elements of the array. The sorting order can be alphabetical or numerical, and in ascending or descending order. The default is alphabetical ascending order; this method has an optional parameter, which must be a function, and the syntax is "array. sort(callback(a,b))".

What is the sorting method of es6 array

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

The sort() method is used to sort the elements of an array.

  • The sort order can be alphabetical or numerical, and in ascending or descending order.

  • The default sort order is ascending alphabetically.

Among them, the sort() method has an optional parameter. However, this parameter must be a function. When calling the sort() method of an array, if no parameters are passed, the elements in the array will be sorted in alphabetical order (character encoding order). If you want to sort according to other criteria, you need to pass a parameter and it is a function. This function Compares two values ​​and returns a number describing the relative order of the two values.

Syntax:

array.sort(callback(a,b))
Parameters Description
callback(a,b)

optional. Specifies the sort order. Must be a function.

#Return value: Array type, which is a reference to the array. Please note that the array is sorted on the original array, no copy is made.

Example:

 //sort的基本使用
  let arr = [8, 1, 4, 3, 7, 9]
  let Arr = [21, 55, 29, 105, 45]
  console.log(arr.sort()) //[1, 3, 4, 7, 8, 9]
  console.log(Arr.sort()) // [105, 21, 29, 45, 55]

What is the sorting method of es6 array

It can be seen from the above code that the sort() method can only correctly sort arrays within 0-9. Although the return value is given for array items with more than 100 digits, they are not the sorted results. This is because sort() performs internal sorting based on ASCLL codes, not based on numerical values. So this method cannot even perform formal sorting on numbers above two digits. How is it different from salted fish?

Here comes the key point: sort() can receive a callback (a, b) that carries two formal parameters, that is, a and b are two elements that are about to be compared in size, and there must be a return value.

  • When the return value of callback is a positive number, then b will be arranged before a;

  • When the return value of callback is a negative number , then a will be arranged before b;

  • When the return value of callback is 0, then the positions of a and b remain unchanged;

  • Every time sort is executed, the positions of the two parameters a and b in the original array will be exchanged based on the return value;

You will be confused after reading the above description, you must Will ask where is the return value? Who is the actual parameter of parameter a b? Once you understand the following code, these are all child’s play!

 //sort 内部写法
  let Arr = [56, 21, 29, 105, 45]
  Arr.sort(function(a, b) { //callback
      if (a > b) { // a b 分别是Arr中的 56 21
          return 1  //返回正数 ,b排列在a之前
      } else {
          return -1 //返回负数 ,a排列在b之前
      }
  })
  console.log(Arr) //[21, 29, 45, 55, 105]

Execution logic:

What is the sorting method of es6 array

It should be noted that the two parameters received by callback(a, b) are a = > current item, b The next item of the current item, if the positions of the current item and the next item remain unchanged, b is the index of the next item -1; the condition for judging the end of the traversal is that the b parameter will end if it cannot obtain a value. For example, the third round in the above code When executing the second time, the index of the current item is 3, then b is the next item, that is, 4. The 4th item cannot be obtained in the array, and the conditions for continuing the traversal are not met, so the traversal ends!

Let’s talk about return values: The return values ​​1 and -1 written in the above code are just symbolic representations of 1 being a positive number and -1 being a negative number. No matter what return value you write in the code, sort will only judge you internally. Whether the return value is a positive number or a negative number, it is feasible to return 100 even if the equation is true or -10000 if it is not true.

Explanation of abbreviation:

What is the sorting method of es6 array

//简写 最终版  
  let Arr = [56, 21, 88, 10, 5, 77]
  Arr.sort((a, b) => a - b) //箭头函数不加大括号指向这个函数的返回值,可以不写return关键字
  console.log(Arr) //[5, 10, 21, 56, 77, 88]

As can be seen from the above figure, the internal processing method of the callback function is a - b, instead of comparing two numbers. . This is because the step of comparing two numbers is done by sort. You only need to specify the return value. Mathematically, it happens that large numbers - decimals = positive numbers, decimals - large numbers = negative numbers

Example If 56 - 21 = 35 is a positive number, the return value is a positive number, and the positive number represents changing the position;

21 - 88 = 35 is a negative number, the return value is a negative number, and the negative number represents changing the position;

If in mathematics, large number - small number ≠ positive number, small number - large number ≠ negative number, it cannot be abbreviated like this. So it should be clear that sort internally compares each other rather than subtracts each other;

[Related recommendations: javascript video tutorial, web front-end]

The above is the detailed content of What is the sorting method of es6 array. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is thedifference between class and id selector?What is thedifference between class and id selector?May 12, 2025 am 12:13 AM

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

CSS IDs vs Classes: The real differencesCSS IDs vs Classes: The real differencesMay 12, 2025 am 12:10 AM

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

CSS: What if I use just classes?CSS: What if I use just classes?May 12, 2025 am 12:09 AM

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and Class Selectors in CSS: A Beginner's GuideID and Class Selectors in CSS: A Beginner's GuideMay 12, 2025 am 12:06 AM

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.

Understanding the HTML5 Specification: Key Objectives and BenefitsUnderstanding the HTML5 Specification: Key Objectives and BenefitsMay 12, 2025 am 12:06 AM

Key goals and advantages of HTML5 include: 1) Enhanced web semantic structure, 2) Improved multimedia support, and 3) Promoting cross-platform compatibility. These goals lead to better accessibility, richer user experience and more efficient development processes.

Goals of HTML5: A Developer's Guide to the Future of the WebGoals of HTML5: A Developer's Guide to the Future of the WebMay 11, 2025 am 12:14 AM

The goal of HTML5 is to simplify the development process, improve user experience, and ensure the dynamic and accessible network. 1) Simplify the development of multimedia content by natively supporting audio and video elements; 2) Introduce semantic elements such as, etc. to improve content structure and SEO friendliness; 3) Enhance offline functions through application cache; 4) Use elements to improve page interactivity; 5) Optimize mobile compatibility and support responsive design; 6) Improve form functions and simplify verification process; 7) Provide performance optimization tools such as async and defer attributes.

HTML5: Transforming the Web with New Features and CapabilitiesHTML5: Transforming the Web with New Features and CapabilitiesMay 11, 2025 am 12:12 AM

HTML5transformswebdevelopmentbyintroducingsemanticelements,multimediacapabilities,powerfulAPIs,andperformanceoptimizationtools.1)Semanticelementslike,,,andenhanceSEOandaccessibility.2)Multimediaelementsandallowdirectembeddingwithoutplugins,improvingu

ID vs. Class in CSS: A Comprehensive ComparisonID vs. Class in CSS: A Comprehensive ComparisonMay 11, 2025 am 12:12 AM

TherealdifferencebetweenusinganIDversusaclassinCSSisthatIDsareuniqueandhavehigherspecificity,whileclassesarereusableandbetterforstylingmultipleelements.UseIDsforJavaScripthooksoruniqueelements,anduseclassesforstylingpurposes,especiallywhenapplyingsty

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools