简体   繁体   English

javascript - 从数组创建多维数组

[英]javascript - Create multidimensional array from array

Hello I would like to create in JavaScript multidimensional array like this:您好,我想在 JavaScript 中创建这样的多维数组:

var multiLayer = [
  ["First", "Second", 4],
  [5, 6, 3],
  [3, 2, 1]
];

From simple array like that从这样的简单数组

var simple = [
  "First",
  "Second",
  4,
  5,
  6,
  3,
  3,
  2,
  1
];

Here is my code yet这是我的代码

var multi = [];
var howMuchBreak = 3;

for (var i = 0; i < simple.length; i++) {
  multi.push(simple[i + howMuchBreak])
}

Variable howMuchBreak defines on which position in the index must be create next nested array.变量 howMuchBreak 定义必须在索引中的哪个位置创建下一个嵌套数组。

You can use Array.slice(start, end) and increment the start by the desired sub-array length:您可以使用Array.slice(start, end)并将开始增加所需的子数组长度:

 var simple = [ "First", "Second", 4, 5, 6, 3, 3, 2, 1 ]; var multiLayer = []; // sub array length, in your example 3 var l = 3; for (var i=0; i<simple.length; i += l) { multiLayer.push(simple.slice(i, i+l)); } console.log(multiLayer);

Another solution, using the remainder % operator.另一种解决方案,使用余数%运算符。 The other answer solves the problem in fewer lines (actually, the other answer does it in 18 i do it in 19) but i am adding this just to acquaint you with the % operator, very useful.另一个答案用更少的行解决了问题(实际上,另一个答案在 18 中解决了我在 19 中完成的问题)但我添加这个只是为了让您熟悉%运算符,非常有用。

Quoting from MDN:引自 MDN:

The remainder operator returns the remainder left over when one operand is divided by a second operand.当一个操作数除以第二个操作数时,余数运算符返回剩余的余数。

Ponder the code and try to find out why and how this operator fits your situation :)思考代码并尝试找出此运算符适合您的情况的原因和方式:)

 var simple = [ "First", "Second", 4, 5, 6, 3, 3, 2, 1 ]; var multi = []; var sub_array_length = 3; for (var i = 0; i < simple.length; i++) { if(i % sub_array_length === 0) { multi[multi.length] = []; } multi[multi.length - 1].push(simple[i]); } console.log(multi);

or using while...或使用 while ...

var arr=[1,2,3,4,5,6,7,8,9,10]
var array = [], chunk = 3;

while (arr.length > 0){ array.push(arr.splice(0, chunk)); }

console.log(array);

I made three variations:我做了三个变体:

First - Adaptive limiter第一 - 自适应限制器

What it does is, well, do what you want but adapt if there's space left.它的作用是,好吧,做你想做的,但如果有剩余空间,就适应。

Example:示例:

  • Array: [1,2,3,4,5]数组: [1,2,3,4,5]
  • Break by: 2突破: 2
  • Will generate: [ [1,2], [3,4], [5] ]将生成: [ [1,2], [3,4], [5] ]

    var simple = [ "First", "Second", 4, 5, 6, 3, 3, 2, 1 ]; var simple = [ "第一", "第二", 4, 5, 6, 3, 3, 2, 1 ];

     var multi = []; var howMuchBreak = 2; var i = 0; // start counting simple array elements var x = 0; // start counting limited array elements while (i < simple.length) { var limitedArray = []; x = 0; while (x < howMuchBreak && i < simple.length) { limitedArray.push(simple[i]); x++; i++; } multi.push(limitedArray); }

Second - Non-adaptive limiter第二 - 非自适应限制器

Also does what you want but it doesn't adapt to extra space.也可以做你想做的事,但它不适应额外的空间。

Example:示例:

  • Array: [1,2,3,4,5]数组: [1,2,3,4,5]
  • Break by: 2突破: 2
  • Will generate: [ [1,2], [3,4], [5, undefined] ]将生成: [ [1,2], [3,4], [5, undefined] ]

    var simple = [ "First", "Second", 4, 5, 6, 3, 3, 2, 1 ]; var simple = [ "第一", "第二", 4, 5, 6, 3, 3, 2, 1 ];

     var multi = []; var howMuchBreak = 2; var i = 0; // start counting simple array elements var x = 0; // start counting limited array elements while (i < simple.length) { var limitedArray = []; x = 0; while (x < howMuchBreak) { limitedArray.push(simple[i]); x++; i++; } multi.push(limitedArray); }

Third - ES6 API-like第三个 - 类似 ES6 API

It does the same as the others above but with more elegance.它和上面的其他人一样,但更优雅。 Also, I wanted to introduce you to new features of javascript to improve your code.此外,我想向您介绍 javascript 的新功能,以改进您的代码。

That code uses a config JSON with two properties:该代码使用具有两个属性的配置 JSON:

  • adaptive: <boolean> (defaults to true)自适应: <boolean> (默认为真)
  • breakBy: <integer> breakBy: <integer>

Simply pass the simple array first and then the config to the simpleToMulti function:只需先传递简单数组,然后将配置传递给 simpleToMulti 函数:

let multi = simpleToMulti( simpleArray, config );

Example 1:示例 1:

  • Array: [1,2,3,4,5]数组: [1,2,3,4,5]
  • config: { adaptive: true, breakBy: 3 }配置: { adaptive: true, breakBy: 3 }
  • Will generate: [ [1,2,3], [4,5] ]将生成: [ [1,2,3], [4,5] ]

Example 2:示例 2:

  • Array: [1,2,3,4,5]数组: [1,2,3,4,5]
  • config: { adaptive: false, breakBy: 2 }配置: { adaptive: false, breakBy: 2 }
  • Will generate: [ [1,2], [3,4], [5, undefined] ]将生成: [ [1,2], [3,4], [5, undefined] ]

     let simple = ["First", "Second", 4, 5, 6, 3, 3, 2, 1]; let config = { breakBy: 4, adaptive: true }; function simpleToMulti(arr, config) { // normalize config if (config.breakBy === undefined) { console.warn('simpleToMulti: You must inform the breakBy config property'); return; } config.adaptive = config.adaptive === undefined ? true : config.adaptive; // do the magic let limitedArray = []; let multiArray = []; arr.forEach( value => { if (limitedArray.length < config.breakBy) { limitedArray.push(value); } if (limitedArray.length === config.breakBy) { multiArray.push(limitedArray); limitedArray = []; } }); if (limitedArray.length !== 0) { if (config.adaptive) { multiArray.push(limitedArray); } else { while (limitedArray.length < config.breakBy) { limitedArray.push(undefined); } multiArray.push(limitedArray); } } return multiArray; } let multi = simpleToMulti(simple, config); console.log(multi);

I've been spending the last hour trying to find a way to create a multidimensional array from an array of ints.我花了最后一个小时试图找到一种方法来从整数数组创建多维数组。 This is what I finally came up with ( reduceRight and times are from the lodash library ).这就是我最终reduceRightreduceRighttimes来自lodash 库)。

let dimensions = [1, 2, 3]

_.reduceRight(dimensions, (result, dimension) => {
    return _.times(dimension, () => result)    
}, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM