如何從兩個數組創建一個數組

[英]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.

我如何把這兩個數組給我一個名為“arrayNeeded”的數組。這就是我所做的。我是javascript的學習者,所以它有點混亂。

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

obj是一個對象,其中有兩個數組lgan和lgaid

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

結果給了我一個像這樣的字符串數組(“['Student Count',9890]”)而不是一個2列數組的數組

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

Please, someone, help me out. Thanks.

請有人幫助我。謝謝。

4 个解决方案

#1


1  

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']);

#2


1  

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.

結果數組位於所需的數組中。

#3


0  

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.

通過使用Array#map映射一個數組來創建一個新數組。回調中的第二個參數是當前索引,您可以使用它從另一個數組中獲取該項。

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

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

console.log(result);

#4


0  

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);


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/09/07/72fb96dc0c97a1067512fd9672a665e1.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com