การ Sort ทางฝั่ง Client ถือเป็นการลงทุนน้อยส่วนผลตอบแทนก็ขึ้นอยู่กับความเก่งของ Web Browser ซึ่งปัจจุปันคิดว่าน่าจะได้ผลใกล้เคียงกันแทบทุกค่ายนะ
ตัวอย่างง่ายๆ ที่ผมใช้ Sort โดยไม่ต้องทำหลังบ้านส่งมาให้ทาง Web Browser ทำให้ดังนี้
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>JS Sort Example</title> | |
</head> | |
<body> | |
<h1>Locale Sort Example</h1> | |
<hr/> | |
<h2>No Sort</h2> | |
<ul id="list1"></ul> | |
<hr/> | |
<h2>Sort</h2> | |
<ul id="list2"></ul> | |
<hr/> | |
<h2>Locale Sort TH</h2> | |
<ul id="list3"></ul> | |
<hr/> | |
<h2>Locale Sort EN</h2> | |
<ul id="list4"></ul> | |
<script> | |
function localeSort(Arr,lang){ | |
Arr.sort((a, b) => a.localeCompare(b, lang)) | |
return Arr | |
} | |
StringArray = ['โอกาส','เก่ง','กุ้ง','โข่ง','ขุ่น','แกง','อ่อน','อิ่ม','Apple','action','zebra','Zip'] | |
list1 = document.getElementById('list1') | |
list2 = document.getElementById('list2') | |
list3 = document.getElementById('list3') | |
list4 = document.getElementById('list4') | |
for(i in StringArray){ | |
let node = document.createElement("li") | |
node.append(StringArray[i]) | |
list1.appendChild(node) | |
} | |
StringArray.sort() | |
for(i in StringArray){ | |
let node = document.createElement("li") | |
node.append(StringArray[i]) | |
list2.appendChild(node) | |
} | |
localeSort(StringArray,'th') | |
for(i in StringArray){ | |
let node = document.createElement("li") | |
node.append(StringArray[i]) | |
list3.appendChild(node) | |
} | |
localeSort(StringArray,'en') | |
for(i in StringArray){ | |
let node = document.createElement("li") | |
node.append(StringArray[i]) | |
list4.appendChild(node) | |
} | |
</script> | |
</body> | |
</html> |
จาก Array
['โอกาส','เก่ง','กุ้ง','โข่ง','ขุ่น','แกง','อ่อน','อิ่ม','Apple','action','zebra','Zip']
ลองเอาไปเล่นกันดูครับ
Top comments (0)