Array Sort Custom in JavaScript

Level 4324 keystrokes

This sorts objects by number (price) and by string (name) using custom comparators.

JavaScript code

// Array of objects with name and price
1const items = [
2 { name: "Apple", price: 150 },
3 { name: "Banana", price: 80 },
4 { name: "Orange", price: 120 }
5];
6
// [...items] creates a copy (sort modifies the array)
// For numbers: return negative (a first), positive (b first), or 0
// a.price - b.price sorts ascending by price
7const byPrice = [...items].sort((a, b) => a.price - b.price);
// Result: Banana, Orange, Apple (80, 120, 150)
8console.log(byPrice.map(i => i.name));
9
// For strings: use localeCompare for proper alphabetical sort
// It handles unicode and locale-specific ordering
10const byName = [...items].sort((a, b) => a.name.localeCompare(b.name));
// Result: Apple, Banana, Orange (alphabetical)
11console.log(byName.map(i => i.name));

Output

[ 'Banana', 'Orange', 'Apple' ]
[ 'Apple', 'Banana', 'Orange' ]
Practice typing this code

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.

  • .× 19
  • (× 9
  • )× 9
  • ,× 7
  • =× 7
  • :× 6
  • "× 6
  • ;× 5
  • >× 4
  • [× 3

More JavaScript examples at level 4

← JavaScript typing practice