想象一下,我有一个数组:
A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
我希望它转换成二维数组(N x M矩阵),例如:
A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));
请注意,矩阵的行和列是可更改的。
答案 0 :(得分:42)
这样的东西?
function listToMatrix(list, elementsPerSubArray) {
var matrix = [], i, k;
for (i = 0, k = -1; i < list.length; i++) {
if (i % elementsPerSubArray === 0) {
k++;
matrix[k] = [];
}
matrix[k].push(list[i]);
}
return matrix;
}
用法:
var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);
// result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
答案 1 :(得分:25)
您可以使用Array.prototype.reduce
功能在一行中执行此操作。
ECMAScript 6风格:
myArr.reduce((rows, key, index) => (index % 3 == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows, []);
&#34;正常&#34; JavaScript的:
myArr.reduce(function (rows, key, index) {
return (index % 3 == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows;
}, []);
您可以将3更改为您想要的列数,或者更好,将其置于可重用的函数中:
ECMAScript 6风格:
const toMatrix = (arr, width) =>
arr.reduce((rows, key, index) => (index % width == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows, []);
&#34;正常&#34; JavaScript的:
function toMatrix(arr, width) {
return arr.reduce(function (rows, key, index) {
return (index % width == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows;
}, []);
}
答案 2 :(得分:3)
如下:
var matrixify = function(arr, rows, cols) {
var matrix = [];
if (rows * cols === arr.length) {
for(var i = 0; i < arr.length; i+= cols) {
matrix.push(arr.slice(i, cols + i));
}
}
return matrix;
};
var a = [0, 1, 2, 3, 4, 5, 6, 7];
matrixify(a, 2, 4);
答案 3 :(得分:2)
只需使用两个for循环:
var rowNum = 3;
var colNum = 3;
var k = 0;
var dest = new Array(rowNum);
for (i=0; i<rowNum; ++i) {
var tmp = new Array(colNum);
for (j=0; j<colNum; ++j) {
tmp[j] = src[k];
k++;
}
dest[i] = tmp;
}
答案 4 :(得分:2)
function matrixify( source, count )
{
var matrixified = [];
var tmp;
// iterate through the source array
for( var i = 0; i < source.length; i++ )
{
// use modulous to make sure you have the correct length.
if( i % count == 0 )
{
// if tmp exists, push it to the return array
if( tmp && tmp.length ) matrixified.push(tmp);
// reset the temporary array
tmp = [];
}
// add the current source value to the temp array.
tmp.push(source[i])
}
// return the result
return matrixified;
}
如果您想实际替换数组的内部值,我相信您可以调用以下内容:
source.splice(0, source.length, matrixify(source,3));
答案 5 :(得分:2)
此代码是通用的,无需担心大小和数组,普遍适用
public class Flat
extends ResidentialProperty {
private final DescriptionSupport descriptionSupport = new DescriptionSupport();
@Override
public String getDescription() {
return descriptionSupport.getDescription(this);
}
@Override
public void setDescription(String description) {
descriptionSupport.setDescription(this, description);
}
}
public class DescriptionSupport {
public < T extends HasDescription > String getDescription(T property) {
//i want to call ResidentialProperty's getDescription method
}
public < T extends HasDescription > void setDescription(T property, String description) {
//i want to call ResidentialProperty's setDescription method
}
}
答案 6 :(得分:2)
绊倒自己时,我能想到的最简洁的方法是:
const arrayToMatrix = (array, columns) => Array(Math.ceil(array.length / columns)).fill('').reduce((acc, cur, index) => {
return [...acc, [...array].splice(index * columns, columns)]
}, [])
用法类似
const things = [
'item 1', 'item 2',
'item 1', 'item 2',
'item 1', 'item 2'
]
const result = arrayToMatrix(things, 2)
最终结果是
[
['item 1', 'item 2'],
['item 1', 'item 2'],
['item 1', 'item 2']
]
答案 7 :(得分:1)
function matrixify(array, n, m) {
var result = [];
for (var i = 0; i < n; i++) {
result[i] = array.splice(0, m);
}
return result;
}
a = matrixify(a, 3, 3);
答案 8 :(得分:1)
function chunkArrToMultiDimArr(arr, size) {
var newArray = [];
while(arr.length > 0)
{
newArray.push(arr.slice(0, size));
arr = arr.slice(size);
}
return newArray;
}
//example - call function
chunkArrToMultiDimArr(["a", "b", "c", "d"], 2);
答案 9 :(得分:1)
这是一种将数组转换为二维数组的简单方法,尤其是当您要操纵生成的数组项时。
const arr = [1,2,3,4,5,6,7,8,9]
let i = 0;
let twoDimension = [];
while (i < arr.length) {
const first = arr[i];
const second = arr[i + 1];
const third = arr[i + 2]
let tempArr = []
if (first && second && third) {
tempArr.push(first, second, third)
} else if (first && second) {
tempArr.push(first, second)
} else {
tempArr.push(first)
}
twoDimension[twoDimension.length] = tempArr;
i += 3;
}
console.log(twoDimension)
答案 10 :(得分:0)
CString
答案 11 :(得分:0)
一个很棒的存储库here。
api:masfufa.js
示例:masfufa.html
根据该示例,以下代码段解决了此问题:
jsdk.getAPI('my');
var A=[1, 2, 3, 4, 5, 6, 7, 8, 9];
var MX=myAPI.getInstance('masfufa',{data:A,dim:'3x3'});
然后:
MX.get[0][0] // -> 1 (first)
MX.get[2][2] // ->9 (last)
答案 12 :(得分:0)
使用简答:
const gridArray=(a,b)=>{const d=[];return a.forEach((e,f)=>{const
h=Math.floor(f/b);d[h]=d[h]||[],d[h][f%b]=a[f]}),d};
其中:
a: is the array
b: is the number of columns
很长的答案你可以阅读文章:
答案 13 :(得分:0)
使用Array.from()
的ES6的最简单方法
const matrixify = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size));
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ;
console.log(matrixify(list, 3));
答案 14 :(得分:0)
您可以像这样使用push和slice
var array = [1,2,3,4,5,6,7,8,9] ;
var newarray = [[],[]] ;
newarray[0].push(array) ;
console.log(newarray[0]) ;
输出将为
[[1, 2, 3, 4, 5, 6, 7, 8, 9]]
如果要将数组分为3个数组
var array = [1,2,3,4,5,6,7,8,9] ;
var newarray = [[],[]] ;
newarray[0].push(array.slice(0,2)) ;
newarray[1].push(array.slice(3,5)) ;
newarray[2].push(array.slice(6,8)) ;
您可以使用三行代替
while(array.length) newarray.push(array.splice(0,3));
答案 15 :(得分:0)
又一刺,
function arrayToMatrix(arr, wantedRows) {
// create a empty matrix (wantedRows Array of Arrays]
// with arr in scope
return new Array(wantedRows).fill(arr)
// replace with the next row from arr
.map(() => arr.splice(0, wantedRows))
}
// Initialize arr
arr = new Array(16).fill(0).map((val, i) => i)
// call!!
console.log(arrayToMatrix(arr, 4));
// Trying to make it nice
const arrToMat = (arr, wantedRows) => new Array(wantedRows).fill(arr)
.map(() => arr.splice(0, wantedRows))
(如:this one)
(和:this one from other thread)
扩展一个 Array 以添加到原型中,看起来很有用,它确实需要一些功能来补充 Array 方法,也许有一种 MatArray班级?也适用于多维垫子并将它们弄平,也许,也许不是..