2

I have an array of numbers, like so:

[5, 29, 1, 5, 4919, 109, 17]

I'd like to turn that into pairs of number based on the index in the array, like this:

[[0, 5], [1, 29], [2, 5], [3, 4919], [4, 109], [5, 17]]

How can I do that with javascript?

3 Answers 3

5
[5, 29, 1, 5, 4919, 109, 17].map(function(x,i){return [i,x];})
Sign up to request clarification or add additional context in comments.

Comments

3

The other answer suggests using map which is a fine solution and probably what I would use in my own code, but map was introduced in ECMAScript 5, so it might not work in older browsers (without polyfill).

If you need something more universal, a very simple method would be something like this:

var input = [5, 29, 1, 5, 4919, 109, 17];
var output = [];
for (var i = 0; i < input.length; i++)
    output.push([i, input[i]]);

Or this:

var input = [5, 29, 1, 5, 4919, 109, 17];
var output = Array(input.length);
for (var i in input)
    output[i] = [i, input[i]];

1 Comment

+1 as this is the only answer not using ES5 features without mentioning it.
1

Here's a library that adds those missing methods for older browsers: http://augmentjs.com/ ~ 5.501 kb

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.