admin管理员组文章数量:1420966
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?
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?
Share Improve this question edited Oct 10, 2018 at 13:28 zorro47 asked Oct 10, 2018 at 13:23 zorro47zorro47 2211 silver badge12 bronze badges 2-
2
just switch
w
andh
, sow = Matrix.length;
andh = Matrix[0].length;
– Omar Commented Oct 10, 2018 at 13:28 - Possible duplicate of Merge/flatten an array of arrays in JavaScript? – stealththeninja Commented Oct 10, 2018 at 14:35
3 Answers
Reset to default 6You 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);
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; }
Use forEach for arrays :)
var mergedArr = [];
B.forEach(function(arr){
arr.forEach(function(num){
mergedArr.push(num)
});
});
本文标签: javascriptHow to transform a matrix into array with one rowStack Overflow
版权声明:本文标题:javascript - How to transform a matrix into array with one row - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745331792a2653847.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论