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 排序(數(shù)字屬性)
在前面的示例中,我們按名稱(字符串)進(jìn)行排序。在此示例中,我們將按每個(gè)對(duì)象的 ID 屬性(數(shù)字)進(jìn)行排序。
為此,我們可以使用以下函數(shù):
function byID(a, b) { return parseInt(a.id) - parseInt(b.id) }
在函數(shù)中,我們使用 parseInt()
來(lái)確保該值是一個(gè)數(shù)字,然后我們將兩個(gè)數(shù)字相減以獲得負(fù)值、正值或零值。使用此函數(shù),您可以按公共數(shù)字屬性對(duì)任何對(duì)象數(shù)組進(jìn)行排序。
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'}, ] */
按日期排序
假設(shè)您想要構(gòu)建一個(gè)應(yīng)用程序,允許用戶從數(shù)據(jù)庫(kù)下載姓名列表,但您希望根據(jù)出生日期(從最年長(zhǎng)到最年輕)按時(shí)間順序排列姓名.
此函數(shù)按年、月、日的時(shí)間順序?qū)Τ錾掌谶M(jìn)行排序。
function byDate(a, b) { return new Date(a.dob).valueOf() - new Date(b.dob).valueOf() }
Date().valueOf()
調(diào)用返回每個(gè)日期的時(shí)間戳。然后,我們執(zhí)行與前面示例中相同的減法來(lái)確定順序。
演示:
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'} ] */
這種特殊方法在涉及日期順序的情況下非常方便,例如確定誰(shuí)有資格獲得養(yǎng)老金或其他與年齡相關(guān)的福利的申請(qǐng)。
結(jié)論
總的來(lái)說(shuō),使用各種內(nèi)置方法時(shí),在 JavaScript 中對(duì)元素進(jìn)行排序非常簡(jiǎn)單。無(wú)論您需要對(duì)數(shù)字、字符串、對(duì)象還是日期數(shù)組進(jìn)行排序,都有一種方法可以輕松完成這項(xiàng)工作。借助這些方法,您可以快速輕松地對(duì) JavaScript 應(yīng)用程序中的任何數(shù)據(jù)進(jìn)行排序。
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

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

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

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)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

The key to adding custom rewrite rules in WordPress is to use the add_rewrite_rule function and make sure the rules take effect correctly. 1. Use add_rewrite_rule to register the rule, the format is add_rewrite_rule($regex,$redirect,$after), where $regex is a regular expression matching URL, $redirect specifies the actual query, and $after controls the rule location; 2. Custom query variables need to be added through add_filter; 3. After modification, the fixed link settings must be refreshed; 4. It is recommended to place the rule in 'top' to avoid conflicts; 5. You can use the plug-in to view the current rule for convenience
