Cinecus CC
Published on

แชร์ JavaScript Array Method ที่ใช้บ่อย ๆ ตอนที่ 5 : slice, splice

Overview

วันนี้เราจะมาดู array method ที่ใช้กันบ่อย ๆ อีก 2ตัว คือ slice และ splice ซึ่งชื่ออาจจะคล้าย ๆ กัน แต่วิธีใช้อาจจะแตกต่างกัน ไปดูกันครับ

Array Data

ก่อนอื่นขอสมมติข้อมูล Array ชื่อ cypto_currency ที่เก็บชื่อของเหรียญเป็น string ขึ้นมา เหมือนกับตอนที่แล้ว

index.js
const cypto_currency = ['BTC','ETH','BNB','XRP','ADA','SOL']

slice

slice เอาไว้หั่นข้อมูลใน array โดยรับค่าเข้าไป 2 ตัว คือ index เริ่มต้น และ index สุดท้าย โดย array จะไม่มีการเปลี่ยนแปลงค่าเดิม

array.slice(begin_index,end_index)

ตัวอย่าง : อยากได้เฉพาะข้อมูล 3 อันดับแรก

index.js
const top3 = cypto_currency.slice(0,3)
console.log('cypto_currency',cypto_currency) // สังเกตุว่า array ไม่เปลี่ยนแปลงข้อมูลเดิม
console.log('top3', top3)

ผลลัพธ์

cypto_currency [ 'BTC', 'ETH', 'BNB', 'XRP', 'ADA', 'SOL' ]
top3 [ 'BTC', 'ETH', 'BNB' ]

ตัวอย่าง : อยากเอาตัวแรกออกแต่ไม่อยากใช้ shift ถ้าใช้ slice สามารถใส่แค่ index หน้า อย่างเดียวได้

index.js
const new_cypto_currency = cypto_currency.slice(1)
console.log('new_cypto_currency', new_cypto_currency)

ผลลัพธ์

new_cypto_currency [ 'ETH', 'BNB', 'XRP', 'ADA', 'SOL' ]

splice

splice สามารถทำได้ทั้งลบข้อมูลใน array หรือ เพิ่มข้อมูลใน array โดยเป็นการเปลี่ยนแปลง array เดิม แนวทางการใช้จะคล้าย ๆ pop กับ shift แต่จะเป็น sub array แทน

array.splice(start, deleteCount, item1, item2, ...)

ตัวอย่างแรก : อยากเอาข้อมูล index ที่ 2 และ 3 มาใช้ และลบข้อมูล index ที่ 2 และ 3 ใน array เดิมด้วย

index.js
const sub_cypto_currency = cypto_currency.splice(2,2) // เริ่มที่ index ตัวที่ 2 แล้วนับต่อไปอีก 2 ตัว
console.log('cypto_currency', cypto_currency)
console.log('sub_cypto_currency', sub_cypto_currency)

ผลลัพธ์

cypto_currency [ 'BTC', 'ETH', 'ADA', 'SOL' ]
sub_cypto_currency [ 'BNB', 'XRP' ]

ตัวอย่างที่สอง : อยากเอาแทรกชื่อเหรียญ DOGE และ SHIB เข้าไปใน index ที่ 3 และ 4 ตามลำดับ

index.js
cypto_currency.splice(3,0,'DOGE','SHIB') // เริ่มที่ index ตัวที่ 3 deleteCount ใส่เลข 0 และ argument ต่อๆ ไปคือค่าที่จะแทรก
console.log('cypto_currency', cypto_currency)

ผลลัพธ์

cypto_currency [
  'BTC',  'ETH',
  'BNB',  'DOGE',
  'SHIB', 'XRP',
  'ADA',  'SOL'
]

สรุปการใช้ slice และ splice

  • slice ใช้หั่นเป็น sub array โดย array เดิมไม่เปลี่ยนแปลง
  • splice ใช้หั่นเป็น sub array ได้เหมือนกับ splice แต่ array เดิมเปลี่ยนแปลงด้วย
  • splice ใช้แทรกข้อมูลเข้ามาใน array ตามตำแหน่งที่ต้องการได้

References