Array Sort with Comparator in JavaScript
Level 3120 keystrokes
sort() with a comparator function sorts arrays based on custom criteria.
JavaScript code
// Create an array of objects with name and age1const items = [{ name: "b", age: 30 }, { name: "a", age: 25 }];// Comparator: negative puts a first, positive puts b first, 0 keeps the order// a.age - b.age sorts by age ascending; sort() changes items in place2items.sort((a, b) => a.age - b.age);// Print sorted array (by age ascending)3console.log(items);Output
[ { name: 'a', age: 25 }, { name: 'b', age: 30 } ]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.
,× 4:× 4.× 4"× 4;× 3(× 3)× 3{× 2}× 2=× 2