Build a JSON Data Filter and Sorter
Create a JavaScript function that accepts an array of JSON objects representing products, filters them based on multiple criteria, and then sorts the filtered results by a specified property.
Challenge prompt
You are given an array of product objects, each with properties like name, category, price, and rating. Write a function `filterAndSortProducts(products, filters, sortBy, sortOrder)` that filters this array according to the given filter criteria (category and minimum rating), and then sorts the filtered results by price or rating in ascending or descending order. - `products`: Array of product objects. - `filters`: Object with optional keys `category` (string) and `minRating` (number). - `sortBy`: string, either "price" or "rating". - `sortOrder`: string, either "asc" or "desc". Return the filtered and sorted array. Example: const products = [ {name: "Product A", category: "electronics", price: 99.99, rating: 4.5}, {name: "Product B", category: "clothing", price: 29.99, rating: 4.2}, {name: "Product C", category: "electronics", price: 199.99, rating: 4.8}, ]; filterAndSortProducts(products, {category: "electronics", minRating: 4.5}, "price", "asc"); Should return Product A and Product C, sorted by price ascending.
Guidance
- • Use Array.filter() with conditions based on the filters object to narrow down the products.
- • Use Array.sort() to sort the filtered products according to the specified property and order.
- • Handle cases where filters or sort parameters may be missing or undefined.
Hints
- • Remember to check if filter criteria exist before applying them.
- • For sorting in descending order, reverse the comparison results.
- • Use optional chaining or default parameters to avoid errors when accessing filters.
Starter code
function filterAndSortProducts(products, filters, sortBy, sortOrder) {
// Your code here
}
const products = [
{name: "Product A", category: "electronics", price: 99.99, rating: 4.5},
{name: "Product B", category: "clothing", price: 29.99, rating: 4.2},
{name: "Product C", category: "electronics", price: 199.99, rating: 4.8},
];Expected output
[ {name: "Product A", category: "electronics", price: 99.99, rating: 4.5}, {name: "Product C", category: "electronics", price: 199.99, rating: 4.8} ]
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.