Search code examples
javascriptarrayssub-array

Dividing an array into two arrays


I have an array (rows) with n nodes. Each node contains 6 elements.

Example:

rows[0]: ["1", "Text", "0", "55", "0", "Text 2"]
rows[1]: ["2", "Another Text", "15.5", "55", "16.6", "Another Text 2"]
...
rows[n]: [...]

I want to put the second element (like ["Text", "Another Text", ...]) from all of rows [n] into the separate array

and

I want to put the third and the fifth elements(like [[0, 0], [15.5, 16.6], ...]) into the separate array too. I think I need foreach in the foreach.


Solution

  • This is one of the multiple approaches (It uses Array#forEach),

    let arrays = [
     ["1", "Text", "0", "55", "0", "Text 2"],
     ["2", "Another Text", "15.5", "55", "16.6", "Another Text 2"]
    ];
    
    let withIndex1 = [];
    let withIndex2And4 = [];
    
    arrays.forEach((arr) => {
      withIndex1.push(arr[1]);
      withIndex2And4.push([arr[2],arr[4]]);
    });