将普通数组转换为多维数组

3
我知道已经有类似问题的答案了,但是那个结果并不是我想要的。
我想要将[0,1,2,3,4,5,6,7,8]插入到一个多维数组中,如下所示:

[0,3,6],[1,4,7],[2,5,8]

而不是:

[0,1,2],[3,4,5],[6,7,8]

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

除了使用for...loop之外,是否有更简短的方法来完成它?


请为其他“宽度”添加一些示例。 - Nina Scholz
5个回答

1
你可以使用实际索引取余并将值推送到结果集中。

const
    toMatrix = (array, width) => array.reduce((r, v, i) => {
        (r[i % width] = r[i % width] || []).push(v);
        return r;
    }, []),
    format = array => array.map(a => a.join(' '));

console.log(format(toMatrix([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)));
console.log(format(toMatrix([0, 1, 2, 3, 4, 5, 6, 7, 8], 3)));
console.log(format(toMatrix([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)));
.as-console-wrapper { max-height: 100% !important; top: 0; }


0
你可以尝试这样做。我使用了 "Array.reduce" 和 "Object.values" 来实现这个目标。

var arr = [0,1,2,3,4,5,6,7,8]

var toMatrix = (arr, width) => {

  let gap = Math.ceil(arr.length/width)
  
  return Object.values(arr.reduce((o,d,i) => (o[i%gap] = (o[i%gap] || []).concat(d), o), {}))
}

console.log(toMatrix(arr, 3))

console.log(toMatrix(arr, 2))


已完成 @vibhor1997a 先生!! - Nitish Narang
我的意思是关于命名和可读性,而不是格式。请不要称呼我先生 :) - vibhor1997a

0

input =[0,1,2,3,4,5,6,7,8]

function divideInGroups (array, groupCount) {
 return input.reduce((acc, curr, index)=> {
   let group = index % groupCount;
   if(!acc[group]) acc[group]=[];
   acc[group].push(curr);
   return acc
 },[])
}

console.log("3 Groups", divideInGroups(input,3));
console.log("2 Groups", divideInGroups(input,2));
console.log("1 Groups",divideInGroups(input,1));
console.log("5 Groups",divideInGroups(input,5));


0

如果您愿意,您也可以尝试下面的代码。

function splitToArrays(arr, width=1) {
 /**
  * PARAMETERS:-
  *     arr   : array of numbers (integers in this case)
  *     width : number of elements in each sub array
  */

 let newArr = [];
 let times  = arr.length / width; 

 for(let i = 0; i < width; i++) // each iteration adds a new sub array to newArr
 {
  let step = 0;
  for(let j = 0; j < times; j = j + 1) { // each iteration adds new element to sub array
   
   if(j === 0) {
    let item = arr[i + step]; // fetch item from array
    newArr.push([item]);      // push item to new array
    step += width;
    continue; // continue with next iteration, 
              // skip the following statements
   }

   // else
   let item = arr[i + step]; // 0, 3, 6 | 1, 4, 7
   newArr[i].push(item);
   step += width; // increment step's value by 3 in this case
  }
 }

 // finally
 return newArr;
}


function main() {
 // test case
 let a = [0, 1, 2, 3, 4, 5, 6, 7, 8];
 let b = splitToArrays(a, 3); // 3 denotes number of elements inside sub arrays

 console.log(a);
 console.log(b);
}

main();

/*
 [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
 [ [ 0, 3, 6 ], [ 1, 4, 7 ], [ 2, 5, 8 ] ]
*/


0

虽然已经有许多解决方案发布了,但我仍然要发布我的解决方案,因为我认为它易读、可行,并符合 OP 的用例。

const toMatrix = (arr, width) => arr.reduce((rows, key, index) => {
    let chunkLength = Math.ceil(arr.length / width);
    let rowIndex = Math.ceil(index % chunkLength);
    rows[rowIndex] ? rows[rowIndex].push(key) : rows.push([key]);
    return rows;
}, []);

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]
const toMatrix = (arr, width) => arr.reduce((rows, key, index) => {
    let chunkLength = Math.ceil(arr.length / width);
    let rowIndex = Math.ceil(index % chunkLength);
    rows[rowIndex] ? rows[rowIndex].push(key) : rows.push([key]);
    return rows;
}, []);

console.log(toMatrix(arr, 3));
console.log(toMatrix(arr, 2));
console.log(toMatrix(arr, 1));
console.log(toMatrix(arr, 4));
console.log(toMatrix(arr, 5));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接