If I have 2 strings and I want to return a value based on their alphabetical order

Given two Strings, return 1 if the first is higher in alphabetical order than
the second, return -1 if the second is higher in alphabetical order than the
first, and return 0 if they’re equal

This is my attempt: it must be within the function sortAscending…

function sortAscending(stringOne, stringTwo) {
var alphabet = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z];
for (var i = 0; i<= alphabet.length-1; i++){
    if (stringOne[0] > stringTwo[0]){
        return 1;
} else if (stringOne[0] < stringTwo[0]){
        return -1;
} else if (stringOne[0] === stringTwo[0]){
        return 0;
} 

Let me know if anyone has any insight!

  1. You have an alphabet array, but you never use it. Do you need this array?
  2. Why do you have a for loop if you only ever check the first letter of each string?

@ArielLeslie I know I think I’m making it too confusing. I’m not sure how to compare the letters to determine alphabetical heirarchy

Do you only need to compare the first letter of each string? Does case matter?

Yes, the first letter and I think I need to make it case insensitive.

If you only need to check the first letters, then you don’t need a loop. Go ahead and get rid of those. If you need to be case-insensitive, then you will want to make sure that you aren’t comparing an uppercase with a lowercase. Think about how you can ensure that. If you like, you can use your alphabet array and check a letter’s index. However, you can actually compare characters directly. They are compared by their ASCII value.

Go ahead and Google around some, tinker a bit, and let me know if you get stuck again.

1 Like

Yes, good point. I definitely need to account for that. I’ve been doing some googling, but I’m still stumped.

Wait, scratch that. I’m going to see if I can make the alphabet array into an object instead so that each letter is assigned a numeric value.

would this be a callback for the Array.prototype.sort() method?

you can compare the two strings to each other directly, and it will work, or if you wante case insensitivness you need to do a little something previous than that

i can compare the strings directly, but i need to reference the alphabet to determine their order. this is where i’m stuck

is the referencing the alphabet an instruction for something, or is that the way you want to solve it?

No, not necessarily. I’m just a beginner, so I’m trying to use the tools I have learned so far to solve the problem.

try on your own: console.log("a" > "b"); console.log("aa" > "ab");, you can compare directly
if you still want to use the alphabet array, try with indexOf()