简体   繁体   中英

Compare two strings javascript

Compare the given strings and display the string that comes alphabetically first. Need help with this question, anything I try ends up wrong.

var personName1 = "Ann"; // Code will be tested with different names
var personName2 = "Anthony";

You're looking for the sort feature.

Throw the items into an array, sort them, and return the first result.

 var names = ['Bob', 'James', 'Billy']; console.log (names.sort()[0]) 

Basically you are storing the variables or names in an array and sorting it, when you sort it you will get an array returned and you are fetching it by index zero.

[personName1, personName2].sort()[0]

This is smaller code version of mdawsondev's answer.

Add those variable reference to an array after which you can use sort & localCompare method to get the sorted array

 var personName1 = "Ann"; var personName2 = "Anthony"; var items = [personName1, personName2]; items.sort((a, b) => a.localeCompare(b)); console.log(items) 

The basic thing you need to do is add the two variables you have provided in an array and apply the sort function on them. The sort function will sort the arry in your case in lexicographical order. After sorting the array the first element will return the alphabetically first element. The Code-

[personName1, personName2].sort()[0] Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM