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
INPUTALGORITHMRESULTElectronics$50 TabletBooks$15 NovelBooks$25 GuideElectronics$30 MouseUnsorted Products1Compare by CategoryBooks < Electronics2Then by Price$15 < $25 < $30 < $503Finally by NameApple < Zebra (if needed)4Apply Built-in SortO(n log n) efficiencyBooks$15 NovelBooks$25 GuideElectronics$30 MouseElectronics$50 TabletPerfectly SortedKey Insight:Custom comparators enable multi-criteria sorting in priority order - compare category first, then price, then name.Built-in sort algorithms handle the heavy lifting efficiently at O(n log n) time complexity.TutorialsPoint - Custom Sort Comparator | Built-in Sort with Custom Comparator
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen