Để lọc mảng theo nhiều chuỗi, hãy sử dụng vòng lặp for cùng với indexOf (). Sau đây là mã -
Ví dụ
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 isPresent;
var records = [];
var matchWords = ['John', 'Doe'];
for (var index = 0; index < details.length; index++){
isPresent = true;
for (var outer = 0; outer< matchWords.length; outer++) {
if (details[index].indexOf(matchWords[outer]) === -1) {
isPresent = false;
break;
}
}
if (isPresent){
records.push(details[index]);
}
}
console.log(records) Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đây, tên tệp của tôi là demo151.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau -
PS C:\Users\Amit\JavaScript-code> node demo151.js [ 'My first Name is John and last Name is Doe'