Array Sort with Compare in JavaScript
Level 3160 keystrokes
Uses sort() with compare function to sort numbers in ascending and descending order.
JavaScript code
// Create an array of numbers1const nums = [10, 2, 30, 4, 15];// [...nums] creates a copy to avoid modifying original// sort((a, b) => a - b) sorts ascending: negative means a comes first2const asc = [...nums].sort((a, b) => a - b);// sort((a, b) => b - a) sorts descending: larger numbers come first3const desc = [...nums].sort((a, b) => b - a);// Output ascending order: [2, 4, 10, 15, 30]4console.log(asc);// Output descending order: [30, 15, 10, 4, 2]5console.log(desc);Output
[ 2, 4, 10, 15, 30 ] [ 30, 15, 10, 4, 2 ]
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
.× 10,× 6(× 6)× 6;× 5=× 5[× 3]× 3-× 2>× 2