LearnFrenzy
Sign in Take a free test

String Methods · Predict the Output · Question 15

Natural sort of numeric strings Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What does the following JavaScript code print (console output, as in Node.js)?

main.js
const v = ["10", "9", "100", "9a"];
console.log(v.toSorted(), v.toSorted((a, b) => a.localeCompare(b, undefined, { numeric: true })));
  • A [ '10', '100', '9', '9a' ] [ '9', '9a', '10', '100' ] Correct
  • B [ '9', '9a', '10', '100' ] [ '9', '9a', '10', '100' ]
  • C [ '10', '100', '9', '9a' ] [ '9', '10', '100', '9a' ]
  • D [ '100', '10', '9a', '9' ] [ '9', '9a', '10', '100' ]
Correct Answer: Option A

Default sort compares character by character ("1" before "9"). The numeric option compares the digit runs as numbers: 9 < 10 < 100, and "9a" sorts right after "9".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links