javascript - 从数组创建多维数组

时间:2022-09-25 09:10:22

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定义索引中的哪个位置必须创建下一个嵌套数组。

4 个解决方案

#1


4  

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

#2


2  

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

#3


1  

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

#4


0  

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 = [“First”,“Second”,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 = [“First”,“Second”,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

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)
  • adaptive: (默认为true)
  • breakBy: <integer>
  • breakBy:

Simply pass the simple array first and then the config to the simpleToMulti function:

只需先传递simple数组然后再将config传递给simpleToMulti函数:

let multi = simpleToMulti( simpleArray, config );

let multi = simpleToMulti(simpleArray,config);

Example 1:

例1:

  • Array: [1,2,3,4,5]
  • 数组:[1,2,3,4,5]
  • config: { adaptive: true, breakBy: 3 }
  • config:{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 }
  • config:{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);
    

#1


4  

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

#2


2  

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

#3


1  

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

#4


0  

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 = [“First”,“Second”,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 = [“First”,“Second”,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

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)
  • adaptive: (默认为true)
  • breakBy: <integer>
  • breakBy:

Simply pass the simple array first and then the config to the simpleToMulti function:

只需先传递simple数组然后再将config传递给simpleToMulti函数:

let multi = simpleToMulti( simpleArray, config );

let multi = simpleToMulti(simpleArray,config);

Example 1:

例1:

  • Array: [1,2,3,4,5]
  • 数组:[1,2,3,4,5]
  • config: { adaptive: true, breakBy: 3 }
  • config:{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 }
  • config:{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);