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]]
Wayne
60.5k15 gold badges135 silver badges129 bronze badges
2 Answers 2
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];
})
answered Apr 18, 2011 at 17:55
Wayne
60.5k15 gold badges135 silver badges129 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Yanick Rochon
your JQuery example needs to return
[[i, el]] or it will add two items instead of a nested array of two items.Wayne
@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.Yanick Rochon
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...if sampledata is an array
var sampledata = [10,20,30,40]
var newData = []
jQuery.each(sampledata,function(i,data){newData.push([i,data])})
answered Apr 18, 2011 at 17:41
Naren Sisodiya
7,2882 gold badges27 silver badges35 bronze badges
3 Comments
Kiran
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 ??
Wayne
@Kiran - Use
sampledata[i] where you currently have data. See my answer for a full example.Naren Sisodiya
look at lwburk's response for plain javascript, I've used jQuery
lang-js
var sampledata = [10,20,30,40];