Exercise 3: Sort by Price (ascending) without mutating original

Problem Statement

Function `sortByPrice(items)` banao jo new sorted array return kare. Original array mutate nahi hona chahiye.

Sample Output:

sortByPrice([{price:100},{price:50},{price:200}])
=> [{price:50},{price:100},{price:200}]

Solution

const sortByPrice = (items) => [...items].sort((a, b) => a.price - b.price);

Explanation

Function idea:

  • Input: items array jisme har object me price field hai.
  • Output: naya array jo price ke hisaab se chhote se bada order me sorted hai.
  • Important: original items ko change (mutate) nahi karna.

Part 1: [...items] — copy kyu?

  • [...] spread operator hai.
  • [...items] → ek naya array banata hai jisme items ke hi elements hain.
  • Agar hum directly items.sort(...) karte to original array ka order bhi badal jata.
  • Interview / real projects me immutability (original data safe rakhna) important hota hai.

Part 2: .sort((a, b) => a.price - b.price)

  • sort ko comparator function milta hai ((a, b) => ...).
  • a aur b array ke do elements (yaha product objects) hain.
  • a.price - b.price logic:
  • Agar result negativea ko b se pehle rakho.
  • Agar result positiveb ko a se pehle rakho.
  • Agar 0 → order same rehne do.
  • Iska effect: lowest price sabse pehle, highest price sabse last.

Real world:

  • “Sort by price (Low to High)” dropdown.
  • Course fees / plan prices ko ascending order me dikhana.