freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #23 of 61

array methods · sort · reverse

LambdaVSThe Mutator
Lambda sayssort orders an array (in place) and needs a comparator for numbers; reverse flips it.

sort() defaults to string order, so [10, 2, 1].sort() gives [1, 10, 2]. Pass a comparator: sort((a, b) => a - b) for ascending numbers. Both sort and reverse mutate in place — copy first ([...arr].sort()) if you need the original.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleSort numbers correctly with a comparator, then sort an array of objects by a field.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const nums=[10,2,1,30]; const sorted=[...nums].sort((a,b)=>a-b);
document.getElementById('o').textContent='default='+[...nums].sort()+'\nnumeric='+sorted;</script></body></html>
▶ Open the interactive comic issue
‹ Array Methods · Find · FindIndex · Some · EveryArray Methods · Flat · FlatMap ›