DEV Community

MrChoke
MrChoke

Posted on • Originally published at Medium on

2 2

ตัวอย่างการใช้ LocaleCompare ใน JavaScript

การ Sort ทางฝั่ง Client ถือเป็นการลงทุนน้อยส่วนผลตอบแทนก็ขึ้นอยู่กับความเก่งของ Web Browser ซึ่งปัจจุปันคิดว่าน่าจะได้ผลใกล้เคียงกันแทบทุกค่ายนะ

ตัวอย่างง่ายๆ ที่ผมใช้ Sort โดยไม่ต้องทำหลังบ้านส่งมาให้ทาง Web Browser ทำให้ดังนี้

<!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']
Enter fullscreen mode Exit fullscreen mode

ลองเอาไปเล่นกันดูครับ

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more