Search code examples
javascriptarrayszingchart

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]
  ]
}

Solution

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