Pushing value into a multidimensional array
Try this:
var result = new Array();
for(var i = 0; i < data.length; i++) {
var arr = new Array();
for(var key in data[i]) {
arr.push(data[i][key]);
}
result.push(arr);
}
also if you don't want the 'arr' variable just write directly to the result, but in my opinion code above is much more understandable:
for(var i = 0; i < data.length; i++) {
result.push(new Array());
for(var key in data[i]) {
result[i].push(data[i][key]);
}
}
Ok, based on your comment I have modified the the loop. Please check the solution and mark question as answered if it is what you need. Personally I don't understand why you prefer messy and hard to understand code instead of using additional variables, but that's totally different topic.
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < Object.keys(data[0]).length; j++) {
result[j] = result[j] || new Array();
console.log('result[' + j + '][' + i + ']' + ' = ' + data[i][Object.keys(data[i])[j]])
result[j][i] = data[i][Object.keys(data[i])[j]];
}
}
Prasath K
Skills : HTML5 JavaScript jQuery d3.js SharePoint 2013 Angular.js
Updated on July 09, 2022Comments
-
Prasath K almost 2 years
I have surfed the problem but couldn't get any possible solution ..
Let's say i have a var like this
var data = [ { 'a':10, 'b':20, 'c':30 }, { 'a':1, 'b':2, 'c':3 }, { 'a':100, 'b':200, 'c':300 }];
Now , i need a multidimensional array like
var values = [[10,1,100], //a [20,2,200], //b [30,3,300]]; //c
What i have tried is
var values = []; for(var key in data[0]) { values.push([]); // this creates a multidimesional array for each key for(var i=0;i<data.length;i++) { // how to push data[i][key] in the multi dimensional array } }
Note :
data.length
and number of keys keeps changing and i just want to be done usingpush()
without any extra variables. Even i don't want to use extrafor
loopsIf you guys found any duplicate here , just put the link as comment without downvote