普通数组到多维数组

时间:2018-11-08 07:05:20

标签: javascript multidimensional-array

我知道已经有一个类似问题的答案,但是结果却不是我想要的。

我想将 [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,还有更短的方法吗?

5 个答案:

答案 0 :(得分: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; }

答案 1 :(得分: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))

答案 2 :(得分: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));

答案 3 :(得分: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));

答案 4 :(得分: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 ] ]
*/