Javascript 如何使用Javascript将简单数组转换为二维数组(矩阵)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4492385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:38:01  来源:igfitidea点击:

How to convert simple array into two-dimensional array (matrix) with Javascript

javascriptjqueryarraysmultidimensional-array

提问by Bakhtiyor

Imagine I have an array:

想象一下我有一个数组:

A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);

And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:

我希望它转换为二维数组(N x M 矩阵),例如这样:

A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));

Note, that rows and columns of the matrix is changeable.

请注意,矩阵的行和列是可变的。

回答by jwueller

Something like this?

像这样的东西?

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

Usage:

用法:

var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);
// result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

回答by samanime

You can use the Array.prototype.reducefunction to do this in one line.

您可以使用该Array.prototype.reduce函数在一行中完成此操作。

ECMAScript 6 style:

ECMAScript 6 风格:

myArr.reduce((rows, key, index) => (index % 3 == 0 ? rows.push([key]) 
  : rows[rows.length-1].push(key)) && rows, []);

"Normal" JavaScript:

“普通”JavaScript:

myArr.reduce(function (rows, key, index) { 
  return (index % 3 == 0 ? rows.push([key]) 
    : rows[rows.length-1].push(key)) && rows;
}, []);

You can change the 3 to whatever you want the number of columns to be, or better yet, put it in a reusable function:

您可以将 3 更改为您想要的列数,或者更好的是,将其放入可重用的函数中:

ECMAScript 6 style:

ECMAScript 6 风格:

const toMatrix = (arr, width) => 
    arr.reduce((rows, key, index) => (index % width == 0 ? rows.push([key]) 
      : rows[rows.length-1].push(key)) && rows, []);

"Normal" JavaScript:

“普通”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;
  }, []);
}

回答by Bhanu Prakash H c

This code is generic no need to worry about size and array, works universally

此代码是通用的,无需担心大小和数组,通用

  function TwoDimensional(arr, size) 
    {
      var res = []; 
      for(var i=0;i < arr.length;i = i+size)
      res.push(arr.slice(i,i+size));
      return res;
    }
  1. Defining empty array.
  2. Iterate according to the size so we will get specified chunk.That's why I am incrementing iwith size, because size can be 2,3,4,5,6......
  3. Here, first I am slicing from ito (i+size)and then I am pushing it to empty array res.
  4. Return the two-dimensional array.
  1. 定义空数组。
  2. 根据大小迭代,所以我们会得到指定的块。这就是为什么我用size递增i,因为大小可以是 2,3,4,5,6......
  3. 在这里,首先我从i切片到(i+size)然后我将它推送到空数组res
  4. 返回二维数组。

回答by Andrew Whitaker

How about something like:

怎么样:

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

http://jsfiddle.net/andrewwhitaker/ERAUs/

http://jsfiddle.net/andrewwhitaker/ERAUs/

回答by Vincent Mimoun-Prat

Simply use two for loops:

只需使用两个 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;
}

回答by cwallenpoole

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

If you want to actually replace an array's internal values, I believe you can call the following:

如果你想真正替换一个数组的内部值,我相信你可以调用以下内容:

source.splice(0, source.length, matrixify(source,3));

回答by Calle Bergstr?m

The cleanest way I could come up with when stumbling across this myself was the following:

当我自己偶然发现这个问题时,我能想到的最干净的方法如下:

const arrayToMatrix = (array, columns) => Array(Math.ceil(array.length / columns)).fill('').reduce((acc, cur, index) => {
  return [...acc, [...array].splice(index * columns, columns)]
}, [])

where usage would be something like

使用情况类似于

const things = [
  'item 1', 'item 2',
  'item 1', 'item 2',
  'item 1', 'item 2'
]

const result = arrayToMatrix(things, 2)

where result ends up being

结果最终在哪里

[
  ['item 1', 'item 2'],
  ['item 1', 'item 2'],
  ['item 1', 'item 2']
]

回答by p8ul

This a simple way to convert an array to a two-dimensional array, especially when you want to manipulate array items generated.

这是一种将数组转换为二维数组的简单方法,尤其是当您要操作生成的数组项时。

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)

回答by SayedRakib

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

回答by Jannic Beck

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