Hi, could you provide code for filter document array based on filter criterias with or…
- User
Hi, could you provide code for filter document array based on filter criterias with or and functions
- Assistant
Of course! Here is an example code snippet in JavaScript to filter an array of documents based on filter criteria using both "or" and "and" functions:
const documents = [ { name: 'John', age: 25, city: 'New York' }, { name: 'Alice', age: 30, city: 'Los Angeles' }, { name: 'Bob', age: 35, city: 'Chicago' } ]; const filterCriteria = { $or: [ { age: { $gt: 30 } }, { city: 'New York' } ], $and: [ { name: { $ne: 'Alice' } } ] }; const filteredDocuments = documents.filter(document => { let matchesOrCriteria = false; let matchesAndCriteria = true; if (filterCriteria.$or) { matchesOrCriteria = filterCriteria.$or.some(orCriteria => { return Object.keys(orCriteria).every(key => { if (orCriteria[key].$gt) { return document[key] > orCriteria[key].$gt; } else { return document[key] === orCriteria[key]; } }); }); } else { matchesOrCriteria = true; } if (filterCriteria.$and) { matchesAndCriteria = filterCriteria.$and.every(andCriteria => { return Object.keys(andCriteria).every(key => { if (andCriteria[key].$ne) { return document[key] !== andCriteria[key].$ne; } }); }); } return matchesOrCriteria && matchesAndCriteria; }); console.log(filteredDocuments);