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:
- Number array
- String array
- Complex object array
- By name (string)
- Press ID (number)
- By date of birth (date)
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.
JavaScript sort()
Method
JavaScript 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.
Sort array of numbers
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.
Sort string array in Java script
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"]
Sort arrays of complex objects in JavaScript
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.
Sort objects by name (string attribute)
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 排序(数字属性)
在前面的示例中,我们按名称(字符串)进行排序。在此示例中,我们将按每个对象的 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Wix is suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

WordPress is a Content Management System (CMS). It provides content management, user management, themes and plug-in capabilities to support the creation and management of website content. Its working principle includes database management, template systems and plug-in architecture, suitable for a variety of needs from blogs to corporate websites.

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.
