1

I have an array that looks like:

var myArray = [12, 24, 36, 48, 60, 15, 30];

I need to build a new array of arrays from this to show the index number from the original array in the new array. The final result should look like the following:

var myNewArray = [
    [1, 12],
    [2, 24],
    [3, 36],
    [4, 48],
    [5, 60], 
    [6, 15],
    [7, 30]
];
2
  • What's wrong with looping? Can you show your code so far? Commented Feb 1, 2014 at 23:18
  • @elclanrs I am able to iterate over the array, it's building/pushing the new values of multi arrays into one array that i am having trouble with, i'm not sure where to begin Commented Feb 1, 2014 at 23:19

3 Answers 3

4

You can use Array.prototype.map(), and then generate new array based on value and index of that array.

Demo

var myArray = [12, 24, 36, 48, 60, 15, 30],
    newArray = myArray.map(function (value, index) {
        return [index + 1, value];
    });

FYI: - JavaScript arrays are zero-indexed: the first element of an array is at index 0

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

Comments

2
var myArray= [12, 24, 36, 48, 60, 15, 30], 
myArrayIndexed= myArray.map(function(itm, i){
    return [i+1, itm];
});
myArrayIndexed.join(']\n[');


/* returned value: */ [
    [1, 12],
    [2, 24],
    [3, 36],
    [4, 48],
    [5, 60],
    [6, 15],
    [7, 30]
]

Comments

1

It's as simple as that:

var myArray = [12, 24, 36, 48, 60, 15, 30];
var myNewArray = [];
for (var i = 0; i < myArray.length; i++) {
    myNewArray.push([i+1,myArray[i]]);//or just i depending on the index you need
}

Even a faster way is to cache the length of the array:

for (var i = 0, var l = myArray.length; i < l; i++) {}

To my knowledge and research so far - Javascript's native for loop is quicker than array map for iterating through the array. Here is an interesting benchmark.

Hope this helps!

Comments

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.