google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Sắp xếp một mảng JavaScript Trong ngôn ngữ lập trình JavaScript, chúng ta được cung cấp phương thức sort() để sắp xếp dữ liệu của một mảng, nhưng phương thức này vẫn có thể được dùng để sắp xếp các dữ liệu khác, và bài viết này sẽ trình bày cho bạn các phương thức sắp xếp dữ liệu phổ biến.


Nhãn: sắp xếp, mảng, ngôn ngữ lập trình, phương thức, phổ biến

Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

In JavaScript, we are given a method Sort() to perform sorting. Although Sort() is said to be used for sorting an array, it can also be used to sort anything other than an array itself. In this article we will discuss all about JavaScript array.

Sort() in JavaScript

By default, the method Sort() in JavaScript takes a given array and sort it in lexicographical order and not alphabetical order! This means that the Sort() method sort a given array in dictionary order. Let’s consider the following example of Sort method.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]

The above look fine when sorting an array of string but when it comes to number we will face a little problem.

var list =[ 39, 108, 21, 55, 18, 9]
list.sort() //[108, 18, 21, 39, 55, 9]

Looking at the result of the sort function seems to be unsorted but the fact that it is sorted according to lexicographical order does makes it in an ordered form after using the default sort method. Lucky, JavaScript doesn’t force you to follow lexicographic order. You may also define a function to sort them in your own way.

Reverse Sort()

We get our result in lexicographical order after we performed a Sort() function. What if we want the reverse order of the sort function instead? In JavaScript, there is a function Reverse() which can help us to reverse the result of the array in the opposite order of the result. Consider the following example to illustrate Reverse() method in JavaScript.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]
list.reverse() //["Monkey", "Zebra", "Donkey"]

Simple and powerful.

Customize Sort

The default Sort() function in JavaScript is quite simple and clear. Now, we will look at how we can customize this sort function. JavaScript Sort function does take in a parameter which is a function. Short to say, Sort() Method will sort your array instructed in the given function. However, the return value of the function must be as follow,

  • returns a value less than 0: parameter ‘a’ value is less than parameter ‘b’ value. ‘a’ come BEFORE ‘b’.
  • returns a value greater than 0: parameter ‘a’ value is more than parameter ‘b’ value. ‘a’ come AFTER ‘b’
  • returns exactly 0: parameter ‘a’ and ‘b’ have the same value. no change.

With the above rule, we can create a function that sort our array in numerical order instead of lexicographic order.

function sortmyway(data_A, data_B)
{
	if ( data_A < data_B ) // data_A come before data_B
		return -1;
	if ( data_A > data_B ) // data_A come After data_B
		return 1;
	return 0; // data_A == data_B, no change.

}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

The above example look good but the function seems to be a bit lengthy. You can change the comparison statement in a shorter form using the ‘?’ symbol and we will get a shorter version of the code above.

function sortmyway(data_A, data_B)
{
return ((data_A < data_B) ? -1 : ((data_A > data_B) ? 1 : 0));
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

We can even shorten the above declaration to perform the same task as shown below,

function sortmyway(data_A, data_B)
{
	return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]

All the methods above sort the array in ascending order.

Sort Descending order

Using the shortest method i have above, i can declare a sorting function which sort in descending order as follow,


function sortmyway(data_A, data_B)
{
	return (data_B - data_A);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[108, 55, 39, 21, 18, 9]

You can also achieve this by using the Reverse() method to eliminate the need to declare two sort function for ascending and descending order.

Random Sort Array

Well, we can also take advantage of the sort function to randomize our array. This way, we do not have to perform any loop which also contribute to function efficiency.

function sortmyway(data_A, data_B)
{
	return 0.5 - Math.random(); //random gives us result between 0 and 1
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[21, 9, 39, 108, 18, 55]

Summary

Other than array, we can also sort unordered and ordered list. Sort() method in JavaScript can help us perform different kind of sorting in every type of element not restricting to array only. However, using JavaScript to perform sort of other element other than array can be a lot of pain. Personal advice is to use JavaScript framework such as jQuery or Mootools to ease the job. On the other hand, Sort() method can also be used to substitute unnecessary loop to create a more efficient code especially when comparing each element in an array is required. (we just have to eliminate the return value to perform such task) . Even eliminating duplication in an array is possible with Sort() method!

You can find more JavaScript codes for sorting an Array at here: Algorithms by JavaScript

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web