ObiJuan
ObiJuan

Reputation: 1

Javascript String Sorting

I am trying to wrap my head around sorting in Javascript when it comes to strings. Ok so i have this function here:

var numericalOrder = function(array){
    if(arguments.length === 0 || !Array.isArray(array)){
        throw new Error();
    }
    var anyChange;
    for(var i = 0; i < array.length - 1; i++){
        anyChange = false;
        for(var x = 0; x < array.length - 1; x++){
            if(array[x] > array[x + 1]){
                anyChange = true;
                var temp = array[x];
                array[x] = array[x + 1];
                array[x + 1] = temp;
            }
        }
        if(!anyChange){
            return array;
        }
    }
    return array;
};

When given an array of numbers the function will arrange the values in numerical order, but what i'm confused about is how this same function is able to alphabetize an array of strings. I know there is an array sort() method in javascript but I'm trying to fully grasp this concept. Any help is appreciated :)!

Upvotes: 0

Views: 113

Answers (3)

Luis Garc&#237;a
Luis Garc&#237;a

Reputation: 58

If you want to compare strings You could use "".charCodeAt() ( that gets the ascii number of a character ) but I'd compare directly both strings since "before" < "after" === false

Upvotes: 0

Allan Nienhuis
Allan Nienhuis

Reputation: 4121

your function will sort both numbers and strings, because JavaScript will attempt to compare any two variables with the > operator, and do it's best to ensure that the comparison will make sense. It will even coerce the type of the operands into 'like' types as best it can. So if you compare "a" > 1, it will turn the 1 into the string "1" before making the comparison. But if you compare "0" > 1, I believe it will turn the "0" into 0 before making the comparison. This type conversion happens all the time in JavaScript, leading to some very strange results, such as "false" === true :)

Upvotes: 0

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

> can compare strings so your function works even if the array members are strings.

'a'>'b' === false 'c'>'b' === true

Upvotes: 1

Related Questions