Filling Arrays of Arrays in a for loop getting 2nd Value

Viewed 25

How to get the second value and add it along with the first value in the new array.

 // props.data starting array 

    0: (2) ["datapoint1", "1"]
    1: (2) ["datapoint2", "2"]
    2: (2) ["datapoint3", "3"]
    3: (2) ["datapoint4", "4"]


// The result 
0: (2) ["1", "1"]
1: (2) ["2", "2"]
2: (2) ["3", "3"]
3: (2) ["4", "4"]

//The desired result

0: (2) ["1", "2"]
1: (2) ["3", "4"]

Here is what im doing so far..

    var arr = [];
   var z = 0;
    for (var i = 0; i < props.data.length; i++) {
    
     arr[i] = ( [props.data[i][1], props.data[i][1], ] )

    }
1 Answers

Why not increment by two?

const
    props = { data: [["datapoint1", "1"], ["datapoint2", "2"], ["datapoint3", "3"], ["datapoint4", "4"]] },
    arr = [];

for (let i = 0; i < props.data.length; i += 2) {
    arr.push([props.data[i][1], props.data[i + 1][1]]);
}

console.log(arr);

Related