开发者

How do I sort an array in JavaScript?

开发者 https://www.devze.com 2023-03-04 02:27 出处:网络
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:

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 !!');
0

精彩评论

暂无评论...
验证码 换一张
取 消