เมธอด map() ใช้สำหรับ สร้างอาร์เรย์ใหม่ โดยนำแต่ละองค์ประกอบในอาร์เรย์เดิมผ่านฟังก์ชัน callback แล้วเก็บผลลัพธ์ไว้ในอาร์เรย์ใหม่ อาร์เรย์เดิมไม่ถูกเปลี่ยนแปลง
ไวยากรณ์ (Syntax)
const newArray = arr.map(callback(currentValue[, index[, array]])[, thisArg])
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: ค่าสัมบูรณ์ (Absolute Value)
<!DOCTYPE html>
<html>
<body>
<h2>Array.map() - Math.abs</h2>
<button onclick="display()">แสดงผล</button>
<p id="demo"></p>
<script>
function display() {
const arr = [1, -2, 3, 4, 5, -6, 7, 8, 9, 10];
const res = arr.map(Math.abs);
document.getElementById("demo").innerHTML = "ต้นฉบับ: " + arr + "<br>ผลลัพธ์: " + res;
// ผลลัพธ์: 1,2,3,4,5,6,7,8,9,10
}
</script>
</body>
</html>
ตัวอย่างที่ 2: ปัดเศษตัวเลข
<!DOCTYPE html>
<html>
<body>
<h2>Array.map() - Math.round</h2>
<p id="demo"></p>
<button onclick="display()">ปัดเศษ</button>
<script>
const arr = [11.4, 12.9, 25.6, 88.9];
document.getElementById("demo").innerHTML = "ต้นฉบับ: " + arr;
function display() {
const res = arr.map(Math.round);
document.getElementById("demo").innerHTML = "ต้นฉบับ: " + arr + "<br>ปัดแล้ว: " + res;
// ผลลัพธ์: 11,13,26,89
}
</script>
</body>
</html>
ตัวอย่างที่ 3: แปลงอ็อบเจกต์ในอาร์เรย์
const users = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Jane', lastName: 'Smith'}
];
// สร้างอาร์เรย์ชื่อเต็ม
const fullNames = users.map(user => `${user.firstName} ${user.lastName}`);
// ["John Doe", "Jane Smith"]
// เพิ่มคุณสมบัติใหม่
const usersWithId = users.map((user, index) => ({
...user,
id: index + 1,
fullName: `${user.firstName} ${user.lastName}`
}));
คุณสมบัติสำคัญ
- ✅ ไม่เปลี่ยนแปลงอาร์เรย์ต้นฉบับ (Immutable)
- ✅ คืนค่าอาร์เรย์ใหม่ขนาดเท่าเดิมเสมอ
- ✅ Callback รับค่า:
(element, index, array) - ❌ ไม่สามารถหยุดลูปกลางทางได้ (ใช้
forloop หรือfindแทน)
เปรียบเทียบ map vs forEach
| ด้าน | map() | forEach() |
|---|---|---|
| คืนค่า | อาร์เรย์ใหม่ | undefined |
| Mutate ต้นฉบับ | ไม่ | อาจจะ (ถ้าเขียนโค้ดทำ) |
| Chain ได้ | ใช่ | ไม่ |
| ใช้เมื่อ | ต้องการแปลงค่า (transform) | ต้องการ side effect (log, save, etc.) |