0

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";

5 Answers 5

2

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])

Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

am I the only one here who worries about supporting IE11? Just asking.
0

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.

Comments

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.

3 Comments

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. Hope this helps!!!
Please do add that in your answer. Commenting is unnecessary.
[personName1, personName2].sort()[0]
0
var personName1 = "Ann"; // Code will be tested with different names
var personName2 = "Anthony"; // Code will be tested with different names

if (personName1 > personName2)
{
   console.log (personName1);
}
else
{
   console.log (personName2);
}

In this exercise that I take before, the logic is compared variables in JavaScript that's the purpose of the exercise.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.