วิธีเรียง สลับตำแหน่ง Arrayใน javascript
Sep 7, 2018 · 1 min read
ใน javascript มี function สำหรับจัดการตำแหน่งใน array ทำให้ง่ายต่อการ จัดตำแหน่ง เลื่อน item ขึ้นไว้บนสุด หรือเลื่อนตำแหน่งไว้ล่างสุด
สมมติว่ามี js array 1 ชุด
let items = ['one', 'two', 'three', 'four', 'five']
// > (5) ["one", "two", "three", "four", "five"]ต้องการเลื่อน three ไปไว้หน้าสุด โดยใช้วิธีการตัด three แล้วไปวางไว้หน้าสุดของ array ดังนี้
let index = 2
// 2let tmp = items.splice(index, 1)
// "three"items.unshift(tmp[0])
// 5items
// (5) ["three", "one", "two", "four", "five"]
ต้องการเลื่อน one ไปไว้ท้ายสุด ทำคล้ายๆ กับการเลื่อนไปหน้าสุด คือตัด array ตัวนั้นออกแล้วนำไปเพิ่มไว้ท้ายสุดของชุด array
index = 1
// 1tmp = items.splice(index, 1)
// "one"items.push(tmp[0])
// 5items
// (5) ["three", "two", "four", "five", "one"]
ต้องการเลื่อน four ไปไว้หน้า two
index = 2
// 2tmp = items[index]
// "four"items[index] = items[index-1]
// "two"items[index-1] = tmp
// "four"items
// (5) ["three", "four", "two", "five", "one"]
หลังจากนั้นต้องการเลื่อน four ไปไว้หน้า three
index = 1
// 1tmp = items[index]
// "four"items[index] = items[index-1]
// "three"items[index-1] = tmp
// "four"items
// (5) ["four", "three", "two", "five", "one"]
ต้องการเลื่อน two ไปไว้หลัง five
index = 2
// 2tmp = items[index]
// "two"items[index] = items[index+1]
// "five"items[index+1] = tmp
// "two"items
// (5) ["four", "three", "five", "two", "one"]
สรุป
- สิ่งสำคัญในการเลื่อนตำแหน่งคือ ต้องรู้ index ของตำแหน่งนั้นๆ เพื่อจะได้เลื่อนตำแหน่งได้อย่างถูกต้อง
- เราสามารถนำหลักการไปสร้าง function ไว้ใช้งานเพื่อลดการเขียนโค้ดซ้ำ เพิ่มประสิทธิภาพให้กับการทำงาน
