2

Possible Duplicate:
JavaScript Array rotate()

I have a tricky question for you. I have an object who contain different values and I want to change the index of on element so My first element has to become the last or the third or whatever I want. Is that possible in javascript ??

var object = [{0},{1},{2}]

to

var object = [{2},{0},{1}]

This is an example of what I would like to do.

Thanks in advance.

11
  • You can't, as this isn't valid JavaScript. And BTW: you're object var is an array, that contains malformed object literals. Also: don't use possible reserved words as variable names Commented Sep 6, 2012 at 10:57
  • @EliasVanOotegem clearly this is example code Commented Sep 6, 2012 at 10:58
  • @Anzeo: Even so, it makes it too difficult to answer: the way you could sort the array depends on how its containing objects are structured, or is he looking for a way to sort the keys of any type of object? Commented Sep 6, 2012 at 11:00
  • @EliasVanOotegem what does sorting have to do with that?.. Commented Sep 6, 2012 at 11:01
  • @Qnan read the question again Commented Sep 6, 2012 at 11:01

2 Answers 2

3

Your from and to example is a little hard to understand the intent, but based on the body of your question asking

My first element has to become the last or the third or whatever I want

Writing a method to swap 2 elements in an array is easy enough:

function swapElements(a, x, y){
    var temp = a[x];
    a[x] = a[y];
    a[y] = temp;
}

Live example: http://jsfiddle.net/pwY9L/

Sign up to request clarification or add additional context in comments.

3 Comments

This is the only correct answer
It doesn’t look like the OP is swapping in the example.
The example is wacky, there is no obvious correlation between from and to state. I was going on the line of the question "my first element has to become the last or the third or whatever"
1

I assume you mean:

var array = [0,1,2];

It doesn’t really matter if the array contains numbers, objects or whatever. If you want to modify this array, there are many ways to do this in javascript andyou can read up about all the Array prototypes here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array

F.ex, move the last one and place it first:

array.unshift(array.pop());

1 Comment

That was much what I wanted. I used your response to create my own function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.