วิธีเรียง สลับตำแหน่ง Arrayใน javascript

ใน 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
// 2
let tmp = items.splice(index, 1)
// "three"
items.unshift(tmp[0])
// 5
items
// (5) ["three", "one", "two", "four", "five"]

ต้องการเลื่อน one ไปไว้ท้ายสุด ทำคล้ายๆ กับการเลื่อนไปหน้าสุด คือตัด array ตัวนั้นออกแล้วนำไปเพิ่มไว้ท้ายสุดของชุด array

index = 1
// 1
tmp = items.splice(index, 1)
// "one"
items.push(tmp[0])
// 5
items
// (5) ["three", "two", "four", "five", "one"]

ต้องการเลื่อน four ไปไว้หน้า two

index = 2
// 2
tmp = 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
// 1
tmp = 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
// 2
tmp = items[index]
// "two"
items[index] = items[index+1]
// "five"
items[index+1] = tmp
// "two"
items
// (5) ["four", "three", "five", "two", "one"]

สรุป
- สิ่งสำคัญในการเลื่อนตำแหน่งคือ ต้องรู้ index ของตำแหน่งนั้นๆ เพื่อจะได้เลื่อนตำแหน่งได้อย่างถูกต้อง
- เราสามารถนำหลักการไปสร้าง function ไว้ใช้งานเพื่อลดการเขียนโค้ดซ้ำ เพิ่มประสิทธิภาพให้กับการทำงาน

อ้างอิงจาก
https://medium.com/pnpsolution/%E0%B8%A3%E0%B8%A7%E0%B8%A1-function-%E0%B8%82%E0%B8%AD%E0%B8%87-array-%E0%B9%81%E0%B8%A5%E0%B8%B0%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B9%83%E0%B8%99-java-script-769eff0f637a

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade