Custom Sort Comparator - Problem
You are given an array of product objects. Each product has three properties: category (string), price (integer), and name (string).
Sort the products using a custom comparator with multiple criteria:
- First by
category(alphabetically ascending) - Then by
price(numerically ascending) - Finally by
name(alphabetically ascending)
Return the sorted array of products.
Input & Output
Example 1 — Mixed Categories and Prices
$
Input:
products = [{"category":"Electronics","price":50,"name":"Tablet"},{"category":"Books","price":15,"name":"Novel"},{"category":"Books","price":25,"name":"Guide"},{"category":"Electronics","price":30,"name":"Mouse"}]
›
Output:
[{"category":"Books","price":15,"name":"Novel"},{"category":"Books","price":25,"name":"Guide"},{"category":"Electronics","price":30,"name":"Mouse"},{"category":"Electronics","price":50,"name":"Tablet"}]
💡 Note:
First sort by category: Books comes before Electronics. Within Books category, $15 Novel comes before $25 Guide by price. Within Electronics, $30 Mouse comes before $50 Tablet.
Example 2 — Same Category, Same Price
$
Input:
products = [{"category":"Books","price":20,"name":"Zebra"},{"category":"Books","price":20,"name":"Apple"}]
›
Output:
[{"category":"Books","price":20,"name":"Apple"},{"category":"Books","price":20,"name":"Zebra"}]
💡 Note:
Same category and price, so sort by name alphabetically: Apple comes before Zebra.
Example 3 — Single Product
$
Input:
products = [{"category":"Games","price":60,"name":"Chess"}]
›
Output:
[{"category":"Games","price":60,"name":"Chess"}]
💡 Note:
Only one product, so the result is the same as input.
Constraints
- 1 ≤ products.length ≤ 1000
- 1 ≤ category.length, name.length ≤ 100
- 1 ≤ price ≤ 10000
- category and name contain only letters and spaces
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code