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:
itemsarray jisme har object mepricefield hai. - Output: naya array jo price ke hisaab se chhote se bada order me sorted hai.
- Important: original
itemsko change (mutate) nahi karna.
Part 1: [...items] — copy kyu?
[...]spread operator hai.[...items]→ ek naya array banata hai jismeitemske 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)
sortko comparator function milta hai((a, b) => ...).aaurbarray ke do elements (yaha product objects) hain.a.price - b.pricelogic:- Agar result negative →
akobse pehle rakho. - Agar result positive →
bkoase 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.