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

กรองอาร์เรย์ด้วยหลายเงื่อนไขสตริงใน JavaScript (Multiple String Filter)

ใช้ for loop วนลูปตรวจสอบทุกคำค้นหาด้วย indexOf()

กรองรายการที่มี ทุกคำ ใน matchWords (AND condition)

ตัวอย่างโค้ด


var details = [
  'My first Name is John and last Name is Smith',
  'My first Name is John and last Name is Doe',
  'Student first Name is John and last Name is Taylor'
];

var matchWords = ['John', 'Doe'];
var records = [];

for (var index = 0; index < details.length; index++) {
  var isPresent = true;
  
  for (var outer = 0; outer < matchWords.length; outer++) {
    // ถ้าหาคำไม่เจอ (-1) -> ไม่ผ่าน
    if (details[index].indexOf(matchWords[outer]) === -1) {
      isPresent = false;
      break;
    }
  }
  
  if (isPresent) {
    records.push(details[index]);
  }
}

console.log(records);
// ['My first Name is John and last Name is Doe']

วิธีรัน

node fileName.js

ผลลัพธ์

[ 'My first Name is John and last Name is Doe' ]

คำอธิบาย

  • ลูปนอก: วนแต่ละรายการใน details
  • ลูปใน: ตรวจสอบว่ามี ทุกคำ ใน matchWords หรือไม่
  • indexOf() === -1 หมายถึงไม่เจอ
  • เป็น AND condition: ต้องมีคำทั้ง "John" และ "Doe"

วิธีทันสมัย: ใช้ filter() และ every()


const records = details.filter(text => 
  matchWords.every(word => text.includes(word))
);
// ผลลัพธ์เหมือนกัน โค้ดกระชับกว่า

กรณี OR Condition (มีคำใดคำหนึ่งก็พอ)


const recordsOr = details.filter(text => 
  matchWords.some(word => text.includes(word))
);