Home> CMS Tutorial> WordPress> body text

JavaScript: Sort organization values

王林
Release: 2023-08-30 20:17:02
Original
624 people have browsed it

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 JavaScriptsort()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'ssort()method works and how to use it to sort arrays of numbers, strings, and objects.

JavaScriptsort()Method

JavaScriptsort()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 thesortmethod:

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, thesort()method sortsnumbersin 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 (aandb), which represent the two values to be sorted. If a positive number is returned, thesort()method will understand thatbshould be sorted beforea. If it returns a negative number,sort()will understand thatashould come beforeb. The function will return a positive number ifb>a, which means ifais less thanb, thenbwill be ataBefore.

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 return1from the function, which means the second name will be first in the sorted array. Otherwise, we return-1, or0if they are equal.

Now, if you run the sort method on thenamesarray, withdescas 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 thesort()method. Let's see how in the section below.

Sort objects by name (string attribute)

Here we have apeoplearray containing multiple person objects. Each object consists ofid,nameanddobproperties:

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 thenameproperty we must create a custom sort function and pass it to thesortmethod:

students.sort(byName)
Copy after login

ThisbyNameThe 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!

source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!