0

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

4
  • Is costs guaranteed to only contain 3 arrays or can it be any number? Commented Feb 24, 2015 at 12:02
  • @Magrangs it can be any number Commented Feb 24, 2015 at 12:03
  • 1
    It's not that hard -> jsfiddle.net/d1mbf71v Commented Feb 24, 2015 at 12:18
  • @adeneo Worth noting that the map function will only work in IE9 or later. Commented Feb 24, 2015 at 12:55

1 Answer 1

2

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));

Sign up to request clarification or add additional context in comments.

1 Comment

this outputs only three arrays instead of four

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.