JavaScript Array sort()
ตัวอย่าง
จัดเรียงอาร์เรย์:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
เรียงลำดับแล้วกลับลำดับ:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
ความหมายและการใช้งาน
การsort()
เรียงลำดับองค์ประกอบของอาร์เรย์
จะsort()
เขียนทับอาร์เรย์เดิม
จัดsort()
เรียงองค์ประกอบเป็นสตริงตามลำดับตัวอักษรและจากน้อยไปมาก
ดูสิ่งนี้ด้วย:
จัดเรียงฟังก์ชันเปรียบเทียบ
การเรียงลำดับตามตัวอักษรทำงานได้ดีสำหรับสตริง ("Apple" มาก่อน "Banana")
แต่การเรียงลำดับตัวเลขอาจทำให้ได้ผลลัพธ์ที่ไม่ถูกต้อง
"25" มากกว่า "100" เพราะ "2" มากกว่า "1"
คุณสามารถแก้ไขได้โดยระบุ "ฟังก์ชันเปรียบเทียบ" (ดูตัวอย่างด้านล่าง)
ไวยากรณ์
array.sort(compareFunction)
พารามิเตอร์
Parameter | Description |
compareFunction |
Optional. A function that defines a sort order. The function should return a negative, zero, or positive value, depending on the arguments:
When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. Example: The sort function will sort 40 as a value lower than 100. When comparing 40 and 100, sort() calls the function(40,100). The function calculates 40-100, and returns -60 (a negative value). |
คืนมูลค่า
อาร์เรย์ที่มีการจัดเรียงรายการ |
ตัวอย่างเพิ่มเติม
เรียงลำดับตัวเลขจากน้อยไปมาก:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
เรียงลำดับตัวเลขจากมากไปน้อย:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
ค้นหาค่าต่ำสุด:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order
points.sort(function(a, b){return a-b});
let lowest = points[0];
ค้นหาค่าสูงสุด:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in descending order:
points.sort(function(a, b){return b-a});
let lowest = points[0];
ค้นหาค่าสูงสุด:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order:
points.sort(function(a, b){return a-b});
let highest = points[points.length-1];
รองรับเบราว์เซอร์
sort()
เป็นคุณลักษณะ ECMAScript1 (ES1)
ES1 (JavaScript 1997) ได้รับการสนับสนุนอย่างสมบูรณ์ในเบราว์เซอร์ทั้งหมด:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |