MrFoh
MrFoh

Reputation: 2701

Create an array of first element of each array

I have an array in maxtrix form like this

var costs = [
        [4, 6, 8, 8],
        [6, 8, 6, 7],
        [5, 7, 6, 8],
    ];

how do i transform it to this

 [[4,6,5], [6,8,7], [8,6,5], [8,7,5]]

This is what am trying

var cols = [];

for(var i = 0; i<costs.length; i++)
{
    cols.push(costs[i][0]);
}

return col;

And this gives me [4,6,5]. I know am missing something, any help will be great. Thanks

Upvotes: 0

Views: 47

Answers (1)

ByteHamster
ByteHamster

Reputation: 4951

You need another for loop inside the first one:

var costs = [
    [4, 6, 8, 8],
    [6, 8, 6, 7],
    [5, 7, 6, 8],
];

alert("Original: " + JSON.stringify(costs));

// Prepare array...
var cols = new Array(costs[0].length);
for(var i = 0; i < costs[0].length; i++) {
    cols[i] = new Array(costs.length);
}

// Assign values...
for(var i = 0; i < costs.length; i++) {
    for(var k = 0; k < costs[i].length; k++) {
        cols[k][i] = costs[i][k];
    }
}

alert("New: " + JSON.stringify(cols));

Upvotes: 2

Related Questions