Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript filter(): คู่มือกรอง Array ด้วย Callback Function

เมธอด JavaScript filter() สร้าง array ใหม่จาก array เดิม โดยรับ callback function มาตรวจสอบว่าแต่ละ element ควรเพิ่มเข้า array ใหม่หรือไม่


Array: บทนำสรุป

JavaScript array เก็บ items 0 หรือมากกว่า items อาจเป็น numbers, arrays อื่น, strings หรือ data types อื่น ใช้ numbered indices เริ่ม 0 เข้าถึง item เฉพาะได้

let names = ["Alex", "Bill", "Connor", "Daniel", "Edna"];

JavaScript Filter Array

filter() สร้าง array ใหม่จาก array เดิม โดย evaluate callback function บนแต่ละ item item ที่ผ่านเงื่อนไขใน callback จะถูกเพิ่มเข้า array ใหม่

Syntax

var newArr = oldArr.filter(function(item) {
  return yourCondition;
});

Callback function คืนค่า true/false ถ้า true item นั้นจะอยู่ใน array ใหม่ เงื่อนไขตัวอย่าง:

  • item > 5
  • item == "Jessie"
  • item < 3

ใช้ comparison operators หรือ if statement ใน callback ก็ได้

ตัวอย่างการใช้งาน

1. กรองตัวเลข: รายการซื้อที่มากกว่า $10

var purchases = [2.50, 2.70, 10.50, 12.30, 9.60, 2.30, 3.40];

var big_purchases = purchases.filter(function(purchase) {
  return purchase > 10;
});

console.log(big_purchases); // [10.5, 12.3]

โปรแกรมเช็คว่า purchase > 10 ถ้าใช่เพิ่มเข้า big_purchases

2. กรอง Array of Objects: นักเรียนชั้นปีที่ 1

var students = [
  { id: 1, name: "Alex", class: "First Grade", age: 5 },
  { id: 2, name: "Bill", class: "First Grade", age: 5 },
  { id: 3, name: "Connor", class: "Second Grade", age: 6 }
];

var firstGradeStudents = students.filter(function(student) {
  return student.class === "First Grade";
});

console.log(firstGradeStudents);
// [{ id: 1, name: "Alex", class: "First Grade", age: 5 },
//  { id: 2, name: "Bill", class: "First Grade", age: 5 }]

filter() วนทุก object ใน array คืนค่าที่ class === "First Grade" สร้าง array ใหม่เข้าถึงได้ผ่าน variable firstGradeStudents

สรุป

ใช้ filter() array method สร้าง array ใหม่จาก array เดิม โดยกรอง element ที่ผ่านเงื่อนไข filter() filters elements ออกจาก array เดิม ตอนนี้คุณใช้ filter() ใน JavaScript ได้อย่างมั่นใจแล้ว!