สมมติว่าเรามีอาร์เรย์ของวัตถุเช่นนี้ -
const arr = [{ 'title': 'Hey',
'foo': 2,
'bar': 3
}, {
'title': 'Sup',
'foo': 3,
'bar': 4
}, {
'title': 'Remove',
'foo': 3,
'bar': 4
}]; เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์เช่นอินพุตแรกและอาร์เรย์ของตัวอักษรสตริงเป็นอินพุตที่สอง
ฟังก์ชันของเราควรเตรียมอาร์เรย์ใหม่ที่มีอ็อบเจ็กต์ทั้งหมดที่มีคุณสมบัติหัวเรื่องบางส่วนหรือทั้งหมดรวมอยู่ในอาร์เรย์อินพุตที่สองของตัวอักษร
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const arr = [{ 'title': 'Hey',
'foo': 2,
'bar': 3
}, {
'title': 'Sup',
'foo': 3,
'bar': 4
}, {
'title': 'Remove',
'foo': 3,
'bar': 4
}];
const filterTitles = ['He', 'Su'];
const filterByTitle = (arr = [], titles = []) => {
let res = [];
res = arr.filter(obj => {
const { title } = obj;
return !!titles.find(el => title.includes(el));
});
return res;
};
console.log(filterByTitle(arr, filterTitles)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
[ { title: 'Hey', foo: 2, bar: 3 }, { title: 'Sup', foo: 3, bar: 4 } ]