Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing value into a multidimensional array

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 using push() without any extra variables. Even i don't want to use extra for loops

If you guys found any duplicate here , just put the link as comment without downvote

like image 259
Prasath K Avatar asked Aug 25 '26 14:08

Prasath K


1 Answers

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]];
  }
}
like image 175
Slawomir Pasko Avatar answered Aug 28 '26 04:08

Slawomir Pasko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!