Cinecus CC
Published on

แชร์ JavaScript Array Method ที่ใช้บ่อย ๆ ตอนที่ 7 : sort, join, concat และอื่น ๆ

Overview

วันนี้จะมาแชร์ Method อื่น ๆ ที่เกี่ยวกับ array โดยจะมีอะไรบ้างไปดูกันครับ

sort

sort เอาไว้เรียงข้อมูลใน array ซึ่งส่วนใหญ่ก็ชอบเรียงข้อมูลที่เป็น number โดยการใช้งานจะเป้นการเปลี่ยนแปลงค่า array เดิม

เรียงจากน้อยไปมาก : array.sort((a,b)=>a-b) เรียงจากมากไปน้อย : array.sort((a,b)=>b-a)

ตัวอย่าง : ต้องการเรียงลำดับรายชื่อจากคะแนน น้อยไปมาก

index.js
const data = [
  {
    name:'John',
    score:5
  },
  {
    name:'Peter',
    score:8
  },
  {
    name:'Mark',
    score:6
  },
  {
    name:'Tony',
    score:10
  }
]

data.sort((a,b)=>a.score-b.score)
console.log('data', data)

ผลลัพธ์

data [
  { name: 'John', score: 5 },
  { name: 'Mark', score: 6 },
  { name: 'Peter', score: 8 },
  { name: 'Tony', score: 10 }
]

join

join เป็น method ที่ใช้เปลี่ยนจาก array เป็น string เชื่อมด้วยค่าที่ใส่เข้าไป

array.join(separator)

ตัวอย่าง : ต้องการเชื่อม string ด้วยเครื่องหมาย -

index.js
console.log(['2022','01','01'].join('-'))

ผลลัพธ์

2022-01-01

concat

concat เป็น method ที่ใช้เชื่อม array 2 อัน

array1.concat(array2)

index.js
const numbers_1 = [1, 2, 3, 4, 5]
const numbers_2 = [6, 7, 8]
const concat_numbers = numbers_1.concat(numbers_2)

console.log('concat_numbers', concat_numbers)

ผลลัพธ์

concat_numbers [
  1, 2, 3, 4,
  5, 6, 7, 8
]

สามารถใช้วิธี destructuring array ได้เหมือนกัน เช่น

[...array1,...array2]

index.js
const numbers_1 = [1, 2, 3, 4, 5]
const numbers_2 = [6, 7, 8]
const concat_numbers = [...numbers_1,...numbers_2]

console.log('concat_numbers', concat_numbers)

ผลลัพธ์

concat_numbers [
  1, 2, 3, 4,
  5, 6, 7, 8
]

reverse

reverse เป็น array method ที่ใช้สลับตำแหน่งใน array จากท้ายมาต้น โดยเป็นการเปลี่ยนแปลงค่าเดิม

array.reverse()

ตัวอย่าง : ต้องการสลับตำแหน่ง array จากท้ายไปต้น

index.js
const alphabet = ['a', 'b', 'c', 'd', 'e', 'f']
alphabet.reverse()

ผลลัพธ์

alphabet [ 'f', 'e', 'd', 'c', 'b', 'a' ]

Set

Set อันนี้อาจจะไม่ใช่ array method แต่เราสามาถลบข้อมูลที่ซ้ำๆกันใน array ได้โดยใช้ set

[...new Set(array)]

ตัวอย่าง : ต้องการเอาเฉพาะค่าที่ไม่ซ้ำกันใน array

index.js
const data = [1, 2, 2, 3, 4, 4, 5, 2, 4, 1, 1, 5, 6]

const result = [...new Set(data)]

console.log('result', result)

ผลลัพธ์

result [ 1, 2, 3, 4, 5, 6 ]

สรุปการใช้ sort, join, concat, reverse, set

  • sort ใช้เรียงข้อมูลใน array
  • join ใช้เชื่อมข้อมูลใน array ให้เป็น string
  • concat รวม array 2 ตัว ให้เป็น array ใหม่
  • set ข้อมูลใน set จะไม่ซ้ำกัน

References