Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a matrix into array with one row

Tags:

javascript

Consider a matrix B= [[6,4,1,2], [5,3,9,7],[1,3,2,1]];. B is a matrix with three rows and four columns. I want to treat it as an array or a vector, namely B1=[6,4,1,2,5,3,9,7,1,3,2,1]. Moreover, I want to have, for instance, that B1[3]=2 - so it's a number, not a vector anymore. I wrote a simple function

function NewArray(Matrix){
var Temp = [];
var w = Matrix[0].length;
var h = Matrix.length;
for (i=0; i<w; i++){
    for (j=0; j<h; j++){
        Temp.push(Matrix[i][j]);
        }
    }
    return Temp;

}

It occours haowever, that it works only, when B is quadratic. What is wrong?

like image 259
zorro47 Avatar asked Apr 02 '26 14:04

zorro47


2 Answers

You can use apply and concat methods in order to write a simplified solution.

B = [[6,4,1,2], [5,3,9,7],[1,3,2,1]]
B1 = [].concat.apply([], B);
console.log(B1);

Another approach is to use spread syntax

B = [[6,4,1,2], [5,3,9,7],[1,3,2,1]]
B1 = [].concat(...B);
console.log(B1);
like image 129
Mihai Alexandru-Ionut Avatar answered Apr 12 '26 13:04

Mihai Alexandru-Ionut


You could take the length of the nested array, instead of a predefined value in advance.

function newArray(matrix) {
    var temp = [],
        i, j, h, w;
    for (i = 0, h = matrix.length; i < h; i++) {
        for (j = 0, w = matrix[i].length; j < w; j++) {
            temp.push(matrix[i][j]);
        }
    }
    return temp;
}

console.log(newArray([[6, 4, 1, 2], [5, 3, 9, 7], [1, 3, 2, 1]]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 42
Nina Scholz Avatar answered Apr 12 '26 13:04

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!