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]
?
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 !!');
精彩评论