-2

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.

Taher A. Ghaleb
  • 5,120
  • 5
  • 31
  • 44
Alexander Vasilchuk
  • 155
  • 1
  • 1
  • 12
  • 1
    Show us what you have tried. Lots of ways to do this using a variety of different loop approaches – charlietfl Dec 02 '18 at 13:14
  • 1
    `rows.map((arr) => arr[n])`? – kind user Dec 02 '18 at 13:15
  • 1
    Try. Always try first - and then show us what was your approach. You'll learn more by doing that than by copy/pasting some of the answers that someone is inevitably going to give you. https://idownvotedbecau.se/noattempt/ – nemanja Dec 02 '18 at 13:20

4 Answers4

1

You can do it with simple Array#map:

const rows = [
   ["1", "Text", "0", "55", "0", "Text 2"],
   ["2", "Another Text", "15.5", "55", "16.6", "Another Text 2"],
];

const r = (d, n) => rows.map((arr) => arr[n]);

console.log(r(rows, 1));
console.log(r(rows, 2));
kind user
  • 40,029
  • 7
  • 67
  • 77
1

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]]);
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

Not so beautiful, but I think more readable:

let row = [
    ["1", "Text", "0", "55", "0", "Text 2"],
    ["2", "Second Text", "15.5", "55", "16.6", "Second Text 2"],
    ["3", "Third Text", "17", "60", "18", "Third Text 2"]
];

let arrA = [], arrB = [];

function newArrA(el, arr) {
    arr.forEach(arrEl => arrA.push(arrEl[el-1]));
}

function newArrB(elA, elB, arr) {

    arr.forEach(arrEl => arrB.push( [ arrEl[elA-1], arrEl[elB-1] ] ) );

}

newArrA(2, row);
// arrA: ["Text", "Second Text", "Third Text"]

newArrB(3, 5, row);
// arrB[0]: ["0", "0"]
// arrB[1]: ["15.5", "16.6"]
// arrB[2]: ["17", "18"]
Peter Claw
  • 21
  • 2
0

You could transpose the matrix and take the wanted columns and transpose again for getting the wanted result.

const
    transpose = (r, a) => a.map((v, i) => [...(r[i] || []), v]),
    array = [["1", "Text", "0", "55", "0", "Text 2"], ["2", "Another Text", "15.5", "55", "16.6", "Another Text 2"]],
    columns = array.reduce(transpose, []),
    ad1 = columns[1],
    ad2 = [columns[2], columns[4]].reduce(transpose, []);

console.log(ad1);
console.log(ad2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392