Home > Article > CMS Tutorial > JavaScript: Sort organization values
If you already know the basics of JavaScript arrays, it's time to take your skills to the next level with more advanced topics. In this series of tutorials, you'll explore the intermediate topic of programming with arrays in JavaScript.
Sorting an array is one of the most common tasks when programming in JavaScript. Therefore, as a JavaScript programmer, it is crucial to learn how to sort arrays correctly because you will be doing this frequently in real-world projects. The wrong sorting technique can really slow down your application!
In the past, web developers had to use third-party libraries like jQuery and write a lot of code to sort values in a list collection. Fortunately, JavaScript has evolved tremendously since then. Now you can sort JavaScript arrays containing thousands of values with just one line of code, without using any third-party libraries.
In this article, I will show you how to sort simple and complex array collections in JavaScript. We will use the JavaScript sort()
method to sort:
By the end of this tutorial, you should have a thorough understanding of how JavaScript's sort()
method works and how to use it to sort arrays of numbers, strings, and objects.
sort()
MethodJavaScript sort()
method is one of the most useful and commonly used array methods in JavaScript. It allows you to quickly and easily sort an array of data elements in ascending or descending order.
You can use this method to sort arrays of numbers, strings, dates, and even objects. sort()
The method works by taking an array of elements and sorting them based on some criteria. A criterion can be a function, comparison operator, or array of values.
Sorting an array of numbers is very simple using the sort
method:
let numbers = [12, 88, 57, 99, 03, 01, 83, 21] console.log(numbers.sort()) // output [1, 12, 21, 3, 57, 83, 88, 99]
In the above code, the sort()
method sorts numbers
in ascending order, which is the default mode.
You can also sort the numbers backward (i.e. in descending order). To do this, you need to create the following custom sort function:
function desc(a, b) { return b - a }
This function accepts two parameters (a
and b
), which represent the two values to be sorted. If a positive number is returned, the sort()
method will understand that b
should be sorted before a
. If it returns a negative number, sort()
will understand that a
should come before b
. The function will return a positive number if b
> a
, which means if a
is less than b
, then b
will be at a
Before.
console.log(numbers.sort(desc)) // output [99, 88, 83, 57, 21, 12, 3, 1]
The next step is how to sort the string array.
Sorting string values is equally simple:
let names = ["Sam", "Koe", "Eke", "Victor", "Adam"] console.log(names.sort()) // output ["Adam", "Eke", "Koe", "Sam", "Victor"]
The following is a function that sorts the same string in descending order:
function descString(a, b) { return b.localeCompare(a); }
If the second name comes alphabetically after the first name, we will return 1
from the function, which means the second name will be first in the sorted array. Otherwise, we return -1
, or 0
if they are equal.
Now, if you run the sort method on the names
array, with desc
as its argument, you get a different output:
console.log(names.sort(descString)) // ["Victor", "Sam", "Koe", "Eke", "Adam"]
So far we have only sorted simple values such as strings and numbers. You can also sort an array of objects using the sort()
method. Let's see how in the section below.
Here we have a people
array containing multiple person objects. Each object consists of id
, name
and dob
properties:
const people = [ {id: 15, name: "Blessing", dob: '1999-04-09'}, {id: 17, name: "Aladdin", dob: '1989-06-21'}, {id: 54, name: "Mark", dob: '1985-01-08'}, {id: 29, name: "John", dob: '1992-11-09'}, {id: 15, name: "Prince", dob: '2001-09-09'} ]
To sort this array by the name
property we must create a custom sort function and pass it to the sort
method:
students.sort(byName)
This byName
The custom sort function takes two objects each time and compares their two name properties to see which one is larger (i.e. alphabetically first):
function byName(a, b) { return a.name.localeCompare(b.name); }
Now, if you run the code again, you will get the following results:
[ {id: 17, name: "Aladdin", dob: '1989-06-21'}, {id: 15, name: "Blessing", dob: '1999-04-09'}, {id: 29, name: "John", dob: '1992-11-09'}, {id: 54, name: "Mark", dob: '1985-01-08'}, {id: 32, name: "Prince", dob: '2001-09-09'} ]
在前面的示例中,我们按名称(字符串)进行排序。在此示例中,我们将按每个对象的 ID 属性(数字)进行排序。
为此,我们可以使用以下函数:
function byID(a, b) { return parseInt(a.id) - parseInt(b.id) }
在函数中,我们使用 parseInt()
来确保该值是一个数字,然后我们将两个数字相减以获得负值、正值或零值。使用此函数,您可以按公共数字属性对任何对象数组进行排序。
console.log(students.sort(byID)) /* [ {id: 15, name: "Blessing", dob: '1999-04-09'}, {id: 17, name: "Aladdin", dob: '1989-06-21'}, {id: 29, name: "John", dob: '1992-11-09'}, {id: 32, name: "Prince", dob: '2001-09-09'} {id: 54, name: "Mark", dob: '1985-01-08'}, ] */
假设您想要构建一个应用程序,允许用户从数据库下载姓名列表,但您希望根据出生日期(从最年长到最年轻)按时间顺序排列姓名.
此函数按年、月、日的时间顺序对出生日期进行排序。
function byDate(a, b) { return new Date(a.dob).valueOf() - new Date(b.dob).valueOf() }
Date().valueOf()
调用返回每个日期的时间戳。然后,我们执行与前面示例中相同的减法来确定顺序。
演示:
console.log(students.sort(byDate)) /* [ {id: 54, name: "Mark", dob: '1985-01-08'}, {id: 17, name: "Aladdin", dob: '1989-06-21'}, {id: 29, name: "John", dob: '1992-11-09'}, {id: 15, name: "Blessing", dob: '1999-04-09'}, {id: 32, name: "Prince", dob: '2001-09-09'} ] */
这种特殊方法在涉及日期顺序的情况下非常方便,例如确定谁有资格获得养老金或其他与年龄相关的福利的申请。
总的来说,使用各种内置方法时,在 JavaScript 中对元素进行排序非常简单。无论您需要对数字、字符串、对象还是日期数组进行排序,都有一种方法可以轻松完成这项工作。借助这些方法,您可以快速轻松地对 JavaScript 应用程序中的任何数据进行排序。
The above is the detailed content of JavaScript: Sort organization values. For more information, please follow other related articles on the PHP Chinese website!