0

I have an array, with arrays inside it that looks like this:

var arr = [
  ["title1", "title2", "title3"],
  ["description1", "description2", "description3"],
  ["id1", "id2", "id3"]
];

And, I want to take every nth value from the arrays and push it into a new object so it looks like this:

 var newArr = [
    ["title1", "description1", "id1"],
    ["title2", "description2", "id2"],
    ["title3", "description3", "id3"],
 ];

I know I can use a for loop in this case, but am unsure how to get every nth value.

EDIT: The solution was transposing a 2D array, as mentioned by CRice.

Shawn Tabrizi
  • 12,206
  • 1
  • 38
  • 69
ethanc
  • 137
  • 2
  • 12

3 Answers3

3

You could reduce the arrays by taking the index from the outer array as index for the inner array and vice versa.

var array = [["title1", "title2", "title3"], ["description1", "description2", "description3"], ["id1", "id2", "id3"]],
    result = array.reduce(
        (r, a, i) => {
            a.forEach((v, j) => (r[j] = r[j] || [])[i] = v);
            return r;
        },
        []
    );

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

Here is a 100% works solution. Work even if length of arr and arr[0] not matches:

    var arr = [
        ["title1", "title2", "title3", "title4"],
        ["description1", "description2", "description3", "description4"],
        ["id1", "id2", "id3", "id4"],
    ];

    var newArr = [];

    if(arr[0]){
        for(var i=0; i<arr[0].length; i++){
            newArr[i] = new Array();

            for(var a=0; a<arr.length; a++){
                if(arr[a][i]){
                    newArr[i].push(arr[a][i])
                }
            }
        }
    }
Vitalii
  • 161
  • 1
  • 10
0

I think for loop will be a good choice for this type of use-case.

var arr = [
    ["title1", "title2", "title3"],
    ["description1", "description2", "description3"],
    ["id1", "id2", "id3"]
];

var resultArray = [];

for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < 3; j++) {
        resultArray[j] = resultArray[j] || [];
        resultArray[j][i] = arr[i][j];
    }
}
console.log(resultArray);
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29