Get the App
SLTechnology News&Howtos  ›  Development  › 

How does js sort array elements

Shulou Source: shulou.com Published: 2022-06-03 17:15:18 11月13日 Update

This article introduces the knowledge of "how to sort array elements by js". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Using the for loop, you can choose bubbling sort.

/ / compare the size of the two adjacent numbers in turn in each round. If the back is smaller than the front, exchange var baccarat / set the value used to change positions var a = [1, var 9, 3, 2, 5, 5, 34, 23, 98, 14] / / Bubble sort for (var ionomy 0 umbelli for (var jung0) J if (a [j] > a [juni1]) {bachela [j] a [j] = a [j + 1] a [juni1] = b} console.log (a)

2. The sort () method can sort array elements according to certain conditions. It is divided into two cases: the method parameter is empty and the function is empty.

When the parameter of the method is empty, the elements in the array are sorted alphabetically from smallest to largest.

Var a = a.sort (); / / sort elements in alphabetical order console.log (a)

When the argument is a function, the array elements are sorted according to the rules specified by the function.

Var a = [1 return, 2, 40, 40, 50, 5, 50, 6, 7] a.sort (function (Arecedence b) {return b) {order from small to big / / return b from big to small}); console.log (a); this is the end of the content of "how to sort array elements by js". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Sorting elements arrays functions parameters methods from small to large small content letters situation more knowledge order utility learning and then two position dilemma Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker NVidia Shulou Technology Shulou Information macOS