Israel Eruoghene
Israel Eruoghene

Reputation: 99

how to create an array from two arrays

I really do not know how to put the question, I hope some one would assist me. this is what I want to achieve anyway. I want to use the google visualization to create charts.

This is what I want to achieve.

var arrayNeeded = [['Population', 'Total Number Per Unit'],['Staff Count', 5686],['Student Count', 9890]];        
    var data = google.visualization.arrayToDataTable(array);

This is what I have:

var arr1 = [5686, 9890];
var arr2 = [Staff Count, Student Count];

How do I put these two arrays to give me the array called "arrayNeeded". here's what I have done. I'm a learner at javascript so it's kinda messy.

var obj = JSON.parse(sessionStorage.getItem('custs'));
var result = [];
for (var i = 0; i < obj.lgaid.length; i++)
{
    result[i] = "['"+obj.lgan[i]+"',"+ parseInt(obj.lgaid[i])+"]";
}

obj is an object with two arrays lgan and lgaid in it

The result gives me an array of strings like this ("['Student Count', 9890]") rather than an array of 2-column arrays

var result = "['Population', 'Total Number Per Unit']","['Staff Count', 5686]","['Student Count', 9890]";

Please, someone, help me out. Thanks.

Upvotes: 2

Views: 6604

Answers (4)

DileepNimantha
DileepNimantha

Reputation: 224

You may try something like this:

var arr1 = [5686, 9890];
var arr2 = ['Staff Count', 'Student Count'];

var result = arr1.map(function(value, index) {
    return [arr1[index], arr2[index]];
});

result.unshift(['Population', 'Total Number Per Unit']);

Upvotes: 2

mechanicals
mechanicals

Reputation: 685

Here is the answer as you needed. Hope this helps

var titleArr = ['Population', 'Total Number Per Unit']
var arr1 = [5686, 9890];
var arr2 = ['Staff Count', 'Student Count'];

var arrayNeeded = [];

arrayNeeded.push(titleArr);

arr1.map(function(item, index){
  var tempArr = [];
  tempArr.push(arr2[index], arr1[index]);
  arrayNeeded.push(tempArr);
});

console.log(arrayNeeded);

Upvotes: 0

divinemaniac
divinemaniac

Reputation: 277

just use this

var required = [['Population', 'Total Number Per Unit']];
for(var i = 0; i < arr2.length; ++i) {
  required.push([arr1[i],arr2[i]]);
}

the result array is in the required array.

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 193358

Create a new array by mapping one the arrays using using Array#map. The 2nd parameter in the callback is the current index, and you can use it to get the item from the other array.

var arr1 = [5686, 9890];
var arr2 = ['Staff Count', 'Student Count'];

var result = arr1.map((v, index) => [arr2[index], v]);

console.log(result);

Upvotes: 0

Related Questions