This article is a mirror article of machine translation, please click here to jump to the original article.

View: 9445|Reply: 0

[JavaScript] Arrays of objects are sorted by the properties of objects

[Copy link]
Posted on 10/24/2018 2:32:52 PM | | |
The most common way to sort arrays is to sort them by the size of the first letter or number of elements in the array



sort() method changes the original array, and sort methods are not strictly sorted by number size.
If you want to sort the array by size, you need to add a comparison function to the sort() method



Compare function compare return value characteristics:

If a is less than b, a should appear before b in the sorted array (i.e. ascending arrangement), returning a value less than 0
If a is equal to b, it returns 0
If a is greater than b, a value greater than 0 is returned

So can we use the sort method to sort the array of objects according to their attributes?
The answer is yes
Just like the above order the array by size and specify the comparison function, only the properties of the object are being compared at this time
Upper code: Sort the following array of objects by age


The final printed result is shown below:

This completes the array of objects sorted according to the object attributes!





Previous:typescrip{filter}t array filters unwanted objects
Next:There is a function here that is really good, you can make money, it is promotion.
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com