简体   繁体   中英

push more than one elements at same index in array

how to push more than one element at one index of a array in javascript?

like i have

arr1["2018-05-20","2018-05-21"];
arr2[5,4];

i want resulted 4th array to be like:

arr4[["2018-05-20",5],["2018-05-21",4]];

tried pushing like this:

arr1.push("2018-05-20","2018-05-21");
arr1.push(5,4);

and then finally as:

arr4.push(arr1);

But the result is not as expected. Please someone help.

Actually i want to use this in zingChart as :

Options Data Create an options object, and add a values array of arrays.

Calendar Values In each array, provide the calendar dates with corresponding number values in the following format.

 options: {
  values: [
    ['YYYY-MM-DD', val1],
    ['YYYY-MM-DD', val2],
    ...,
    ['YYYY-MM-DD', valN]
  ]
}

Your question is not correct at all, since you cannot push more than one element at the same index of an array. Your result is a multidimensional array:

[["2018-05-20",5],["2018-05-21",4]]
  • You have to create a multidimensional array collecting all your data (arrAll)
  • Then you create another multidimensional array (arrNew) re-arranging previous data

Try the following:

 // Your Arrays var arr1 = ["2018-05-20","2018-05-21"]; var arr2 = [5, 4]; //var arr3 = [100, 20]; var arrAll = [arr1, arr2]; //var arrAll = [arr1, arr2, arr3]; // New Array definition var arrNew = new Array; for (var j = 0; j < arr1.length; j++) { var arrTemp = new Array for (var i = 0; i < arrAll.length; i++) { arrTemp[i] = arrAll[i][j]; if (i === arrAll.length - 1) { arrNew.push(arrTemp) } } } //New Array Logger.log(arrNew) 

Assuming the you want a multidimensional array, you can put all the input variables into an array. Use reduce and forEach to group the array based on index.

 let arr1 = ["2018-05-20","2018-05-21"]; let arr2 = [5,4]; let arr4 = [arr1, arr2].reduce((c, v) => { v.forEach((o, i) => { c[i] = c[i] || []; c[i].push(o); }); return c; }, []); console.log(arr4); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM