0

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]?

4
  • 3
    [] is an array, {} would rather denoting an object. Commented May 9, 2011 at 7:59
  • 1
    search in SO using "javascript array sort" 3,067 results. Didn't those results pop up when you where typing your question? Commented May 9, 2011 at 8:05
  • Kooilnc: Maybe he's asking about an O(n) sorting algorithm and not a built in function to do it? At least, that's the feeling I'm getting from read the question Commented May 9, 2011 at 8:09
  • @Soufiane Hassou: turns out his question meant something quite different, as far as I understand. Commented May 9, 2011 at 8:35

1 Answer 1

2

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 !!');
Sign up to request clarification or add additional context in comments.

4 Comments

thanks.. but i am not asking sorting.. i just want to reorder elements for eg: {e,t,m,a} to {t,e,a,m}
@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)
@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'];
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.