最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - constructing two dimensional array dynamically - Stack Overflow

matteradmin8PV0评论

I have some values in JavaScript array as shown

var sampledata = {10,20,30,40};// these values would e 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]]

I have some values in JavaScript array as shown

var sampledata = {10,20,30,40};// these values would e 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]]
Share Improve this question edited Apr 18, 2011 at 17:59 Wayne 60.4k15 gold badges135 silver badges128 bronze badges asked Apr 18, 2011 at 17:34 KiranKiran 1151 gold badge3 silver badges8 bronze badges 2
  • The sample data syntax is invalid. Also, i don't understand what you're trying to achieve. – Felipe Commented Apr 18, 2011 at 17:35
  • Do you mean var sampledata = [10,20,30,40]; – Chandu Commented Apr 18, 2011 at 17:39
Add a ment  | 

2 Answers 2

Reset to default 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];
})

if sampledata is an array

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

comment list (0)

  1. No comments so far