FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Data Merging

20mins

You are given an array of shopping order records. Each record looks like:

[ { user: 8, total: 50, items: ['notebook'] }, { user: 7, total: 150, items: ['pen'] }, { user: 1, total: 10, items: ['eraser'] }, { user: 7, total: 100, items: ['stapler', 'marker'] }, { user: 7, total: 200, items: ['notebook'] }, { user: 2, total: 200, items: ['pencil'] }, { user: 2, total: 200, items: ['marker'] }, ]

Each order has:

  • user: User ID of the order
  • total: Total cost of the order
  • items: Array of purchased items (alphabetical order)

Your task: Implement mergeOrders(orders) to merge orders by user:

  • Sum up totals for the same user.
  • Combine item arrays (deduplicated + sorted alphabetically).
  • Preserve order by keeping the first occurrence of each user.
  • Do not mutate the original input.

Example

mergeOrders(orders); // [ // { user: 8, total: 50, items: ['notebook'] }, // { user: 7, total: 450, items: ['marker', 'notebook', 'pen', 'stapler'] }, // { user: 1, total: 10, items: ['eraser'] }, // { user: 2, total: 400, items: ['marker', 'pencil'] }, // ]

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests