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]?
1 Answer
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 !!');
4 Comments
suba
thanks.. but i am not asking sorting.. i just want to reorder elements for eg: {e,t,m,a} to {t,e,a,m}
KooiInc
@suba: than I suggest you to change your question into: How do I sort an array to a certain predefined order [in Javascript]? (and combine it with te later asked same SO question)
Teneff
@suba what should be the criteria for ordering ? How the function should order the array if it looks like this
['h','e','l','l','o'];Lee Kowalkowski
@suba: If you're not asking about sorting, what does your question mean? Incidentally, the sort() function accepts as a parameter a reference to a function that handles the comparison between two array elements, so you can implement whatever order you can algorithmically conceive: javascriptkit.com/javatutors/arraysort.shtml
[]is an array,{}would rather denoting an object.