Home > OS >  Transforming two one dimensional arrays into one two dimensional array JavaScript
Transforming two one dimensional arrays into one two dimensional array JavaScript

Time:09-17

I have two arrays, both with the same length:

  • x = [0, 1, 2, 3, ..., 1439]
  • y = [12, 55, 23, 46, ..., 99] (random Number between 0 and 100)

I wanna combine it to a two dimensional array like this:

  • z = [[0, 12], [1, 55], [2, 23], [3, 46], ..., [1439, 99]]

How do I do it? Nesting, mapping? Basically the first array is the key. In the end I wanna draw a line graph in D3 and all examples I have found use two dimensional arrays. One is the x axis, the other the y axis. Probably possible another way. Thanks

CodePudding user response:

let x = [0, 1, 2, 3] 
let y = [12, 55, 23, 46]
let z = [];
for(let i=0;i<x.length;i  ){
  z.push([x[i],y[i]])
}
console.log(z)

convert it to 2d array like this

CodePudding user response:

const newArray = [];
const x = [0, 1, 2, 3, ..., 1439], y = [12, 55, 23, 46, ..., 99]

for(let i = 0; i < x.length; i  ){
  newArray.push([x[i], y[i])
}

CodePudding user response:

Thanks a lot, that helped.

     let min = 0;
        let max = 100;
        let x_arr = [];
        let y_arr = [];
        let z_arr = [];
        let z_ars = [];
        let z_arx = [];
        let z_arz = [];
        for (let i = 0; i < 360; i  ) {
            var r = Math.round(Math.random() * (max - min))   min;
            x_arr[i]= i;
            y_arr[i]= r;

            z_arr.push([x_arr[i],y_arr[i]]);

            z_ars.push([y_arr[i]]);
            z_ars.sort(function(a, b){return a - b});

            z_arz.push([x_arr[i]]);
            
        }

        z_arx.push([z_arz,z_ars]);

        console.log(z_arr);
        console.log(z_ars);
        console.log(z_arz);
        console.log(z_arx);

Now I wanna sort the random data and put the two arrays together the same way. But it is not possible to create them separately and combine them the same way. Something has to be done differently.

This almost works but not quite:

            for (let i = 0; i < 360; i  ) {
            var r = Math.round(Math.random() * (max - min))   min;
            x_arr[i]= i;
            y_arr[i]= r;
            z_arr.push([x_arr[i],y_arr[i]]);

            s_arr = y_arr.sort(function(a, b){return a - b});

            komplett.push([x_arr[i],s_arr[i]]);
        }

        console.log(z_arr);
        console.log(s_arr);
        console.log(komplett);
  • Related