Table of Contents
JavaScript sort() Method
Sort array of numbers
Sort string array in Java script
Sort arrays of complex objects in JavaScript
Sort objects by name (string attribute)
按 ID 排序(数字属性)
按日期排序
结论
Home CMS Tutorial WordPress JavaScript: Sort organization values

JavaScript: Sort organization values

Aug 30, 2023 pm 08:17 PM

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]
Copy after login

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
}
Copy after login

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]
Copy after login

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"]
Copy after login

The following is a function that sorts the same string in descending order:

function descString(a, b) {
    return b.localeCompare(a);
}
Copy after login

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"]
Copy after login

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'}
]
Copy after login

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)
Copy after login

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);
}
Copy after login

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'}
]
Copy after login

按 ID 排序(数字属性)

在前面的示例中,我们按名称(字符串)进行排序。在此示例中,我们将按每个对象的 ID 属性(数字)进行排序。

为此,我们可以使用以下函数:

function byID(a, b) {
  return parseInt(a.id) - parseInt(b.id)
}
Copy after login

在函数中,我们使用 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'},
]
*/
Copy after login

按日期排序

假设您想要构建一个应用程序,允许用户从数据库下载姓名列表,但您希望根据出生日期(从最年长到最年轻)按时间顺序排列姓名.

此函数按年、月、日的时间顺序对出生日期进行排序。

function byDate(a, b) {
   return new Date(a.dob).valueOf() - new Date(b.dob).valueOf()
}
Copy after login

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'}
]
*/
Copy after login

这种特殊方法在涉及日期顺序的情况下非常方便,例如确定谁有资格获得养老金或其他与年龄相关的福利的申请。

结论

总的来说,使用各种内置方法时,在 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!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

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 I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

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.

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

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

How much does WordPress cost? How much does WordPress cost? Apr 05, 2025 am 12:13 AM

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.

Should I use Wix or WordPress? Should I use Wix or WordPress? Apr 06, 2025 am 12:11 AM

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.

Is WordPress a CMS? Is WordPress a CMS? Apr 08, 2025 am 12:02 AM

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.

Is WordPress still free? Is WordPress still free? Apr 04, 2025 am 12:06 AM

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.

Why would anyone use WordPress? Why would anyone use WordPress? Apr 02, 2025 pm 02:57 PM

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.

See all articles