I have a JavaScript array that can be built using this code

var Test = [];
Test.push([3, 2]);
Test.push([5, 7]);
Test.push([8, 1]);
Test.push([4, 10]);

What I need to do is change the first value in each item to be in order from 0, the result should look like this:

[0, 2]
[1, 7]
[2, 1]
[3, 10]

I will also accept a jQuery answer.

share|improve this question

3 Answers

up vote 3 down vote accepted
for (var i=0, l=Test.length; i<l; i++){
    Test[i][0] = i;
}
share|improve this answer
for (var i=0; i < Test.length; i++) {
    Test[i][0] = i;
}
share|improve this answer

If you want a jquery-ic answer:

  $(Test).each(function(i) {
        this[0] = i;
    });

The thing I like about this approach is that the each method creates a separate function scope for each loop iteration. Though it is not necessary in this example, it can help reduce headaches caused by unintended variable binding.

INCORRECT - Though works

 $(Test).each(function(i) {
        this[0] = i++;
    });
share|improve this answer
1  
mm, should't i be initialized to 0 somewhere? – Roland Bouman Jan 5 '10 at 0:35
Actually, no. I accidentally left the ++ on the i. The first argument to the each callback is the index (in the case of an array, or the key in the case of an object). Thanks for catching this though. – sberry Jan 5 '10 at 0:39
Neat, didn't know each it worked like that. Thanks for the explanation – Roland Bouman Jan 5 '10 at 1:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.