suba
suba

Reputation: 1

How do I sort an array in JavaScript?

In an array T we have values [b,a,d,c]. How to reorder this array in a single loop in the aim to get [a,b,c,d]?

Upvotes: 0

Views: 224

Answers (1)

Teneff
Teneff

Reputation: 32148

you can use the .sort() method like:

var T = new Array('a', 'd', 'c', 'b');
T.sort();

I don't really understand what do you mean by "reordering" (maybe sorting in some random order :)

however you can always use for for example:

// create new array
var U = new Array();
for (i=0; i<T.length; i++) {

    // some desired condition
    if (T[i] <= 1) {
        // put the value ( T[i] ) on the desired position
        desired_position = ???
        U[desired_position] = T[i];
    }
    else {
        // otherwise put it at the end of the array
        U.push(T[i]);
    }
}

// and here you have the "reordered" array 
alert('the array U is reordered !!');

Upvotes: 2

Related Questions