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

后端 未结 15 1811
独厮守ぢ
独厮守ぢ 2020-11-27 04:26

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 ins

15条回答
  •  隐瞒了意图╮
    2020-11-27 04:49

    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']
    ]
    

提交回复
热议问题