0

I have some values in JavaScript array as shown

var sampledata = {10,20,30,40};// these values would come from database later

I want to create a two dimensional array with these values.

I want to create a array as

var newData = [[0,10],[1,20],[2,30],[3,40]]
2
  • The sample data syntax is invalid. Also, i don't understand what you're trying to achieve. Commented Apr 18, 2011 at 17:35
  • Do you mean var sampledata = [10,20,30,40]; Commented Apr 18, 2011 at 17:39

2 Answers 2

4

Pure JavaScript:

var newData = [];
var sampledata = [10,20,30,40];
for (var i = 0; i < sampledata.length; i++) {
    newData.push([i, sampledata[i]]);
}

Using higher-order functions:

var newData = sampledata.map(function(el, i) {
    return [i, el];
})
Sign up to request clarification or add additional context in comments.

3 Comments

your JQuery example needs to return [[i, el]] or it will add two items instead of a nested array of two items.
@Yanick - I don't have a jQuery example. If you're talking about the example that uses map then, no, it should not return [[i, el]]. The function given to map should return elements of newData, which are one-dimensional arrays.
my mistake. I don't know why, but when I tried the first time on jsfiddle.net, I got [0,10,1,20,2,30,...]. I cannot reproduce this, so I assume it must have been my fault, or something else...
3

if sampledata is an array

var sampledata = [10,20,30,40]
var newData  = []
jQuery.each(sampledata,function(i,data){newData.push([i,data])})

3 Comments

Thank you Naren Sisodiya , i have tried for(var i=0li<sampledata.length;i++) {newData.push([i,data]) its not working , are they both same ??
@Kiran - Use sampledata[i] where you currently have data. See my answer for a full example.
look at lwburk's response for plain javascript, I've used jQuery

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.