สมมติว่าเรามีอาร์เรย์ของออบเจกต์ดังนี้
const arr = [{ 'title': 'Hey', 'foo': 2, 'bar': 3 }, { 'title': 'Sup', 'foo': 3, 'bar': 4 }, { 'title': 'Remove', 'foo': 3, 'bar': 4 }];เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าวเป็นอินพุตแรก และอาร์เรย์ของสตริงค่าคงที่เป็นอินพุตที่สอง
ฟังก์ชันควรเตรียมอาร์เรย์ใหม่ที่ประกอบด้วยออบเจกต์ทั้งหมดที่ property title ถูกนำเข้าไปบางส่วนหรือทั้งหมดในอาร์เรย์สตริงที่สอง
ตัวอย่างโค้ด
โค้ดสำหรับการทำงานนี้จะเป็นดังนี้
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 } ]