如何根据另一个组大小的数组批量分组数组元素?

huangapple go评论75阅读模式
英文:

How to batch group of array elements in reference to another array of group size?

问题

以下是已翻译的内容:

如何按照另一个分组大小的数组来批量分组数组元素?
我尝试了下面的代码。

代码:

var group_size = [1, 3, 5];
var elements = ['a','b','c','d','e','f','g','h','i','j','k','l'];

var output = [];
for (var i=0; i < group_size.length; i++) {
    output.push(elements.slice(i, group_size[i]))
}
console.log(output);

输出:

[['a'], ['b', 'c'], ['c', 'd', 'e']]

但期望的输出是:

[['a'], ['b','c','d'],['e','f','g','h','i'],['j','k','l']]

如果有更多元素,那么这些元素将按照最大组大小元素进行分组。

示例:

输入 = ['a','b','c']
输出 = [['a'], ['b','c']]

输入 = ['a','b','c','d','e']
输出 = [['a'], ['b','c','d'], ['e']]

输入 = ['a','b','c','d','e','f','g','h','i','j','k','l']
输出 = [['a'], ['b','c','d'],['e','f','g','h','i'],['j','k','l']]

输入 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']
输出 = [['a'], ['b','c','d'],['e','f','g','h','i'],['j','k','l','m','n'], ['o','p']]

我尝试了上面的代码,但它有一些限制。
如何在ecma5(js)中实现这个?

英文:

How to batch group of array elements in reference to another array of group size ?
I tried below code.

Code:

var group_size = [1, 3, 5];
var elements = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;];
        
var output = [];
    for (var i=0; i &lt; group_size.length; i++) {
    output.push(elements.slice(i, group_size[i]))
}
console.log(output);

Output:

[[&quot;a&quot;], [&quot;b&quot;, &quot;c&quot;], [&quot;c&quot;, &quot;d&quot;, &quot;e&quot;]]

But expected output:

[[&#39;a&#39;], [&#39;b&#39;,&#39;c&#39;,&#39;d&#39;],[&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;],[&#39;j&#39;,&#39;k&#39;,&#39;l&#39;]]

If there are moe elements, then those elements to be grouped by max group_size element.

Example :

Input = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]
Output = [[&#39;a&#39;], [&#39;b&#39;,&#39;c&#39;]]

Input = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;]
Output = [[&#39;a&#39;], [&#39;b&#39;,&#39;c&#39;,&#39;d&#39;], [&#39;e&#39;]]

Input = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;]
Output = [[&#39;a&#39;], [&#39;b&#39;,&#39;c&#39;,&#39;d&#39;],[&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;],[&#39;j&#39;,&#39;k&#39;,&#39;l&#39;]]

Input = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;,&#39;m&#39;,&#39;n&#39;,&#39;o&#39;,&#39;p&#39;]
Output = [[&#39;a&#39;], [&#39;b&#39;,&#39;c&#39;,&#39;d&#39;],[&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;],[&#39;j&#39;,&#39;k&#39;,&#39;l&#39;,&#39;m&#39;,&#39;n&#39;], [&#39;o&#39;,&#39;p&#39;]]

I tried above code but that's limiting.
How can I do it in ecma5 (js) ?

答案1

得分: 1

以下是已翻译的内容:

  1. 保持对最大组长度的跟踪。
  2. 保持下一个组应该开始的偏移量的跟踪。
  3. 在源数组的范围内切片组。
  4. 如果数组大于所有组的总和,继续切片大小等于最大组长度的块。
function splitIntoGroups (array, groups) {
    let output = [];
    let maxLength = 1;
    for (var i=0, offset=0; i < groups.length && offset < array.length; i++) {
        output.push(array.slice(offset, offset + groups[i]));
        offset += groups[i];
        maxLength = Math.max(maxLength, groups[i]);
    }
    while (offset < array.length) {
        output.push(array.slice(offset, offset + maxLength));
        offset += maxLength;
    }
    return output;
}

let elements = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'];
let groups = [1, 3, 5, 5, 5, 1000];

// 当所有组的总和超过源数组时,它们会被截断以匹配数组
console.log(splitIntoGroups(elements.slice(0, 3), groups));
console.log(splitIntoGroups(elements.slice(0, 5), groups));
console.log(splitIntoGroups(elements.slice(0, 12), groups));
console.log(splitIntoGroups(elements, groups));

// 当所有组的总和不超过源数组时,最大组将重复直到数组末尾
console.log(splitIntoGroups(elements, [1, 3, 5]));
英文:

What do you need for the solution:

  1. Keep a track of the largest group length.
  2. Keep a track of the offset at which the next group should start.
  3. Slice groups while they are within the range of the source array.
  4. If the array is larger than the sum of all groups, continue slicing chunks equal to the length of the largest group.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function splitIntoGroups (array, groups) {
    let output = [];
    let maxLength = 1;
    for (var i=0, offset=0; i &lt; groups.length &amp;&amp; offset &lt; array.length; i++) {
        output.push(array.slice(offset, offset + groups[i]));
        offset += groups[i];
        maxLength = Math.max(maxLength, groups[i]);
    }
    while (offset &lt; array.length) {
        output.push(array.slice(offset, offset + maxLength));
        offset += maxLength;
    }
    return output;
}

let elements = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;,&#39;m&#39;,&#39;n&#39;,&#39;o&#39;,&#39;p&#39;];
let groups = [1, 3, 5, 5, 5, 1000];

// when sum of all groups exceeds the source array,
// they are truncated to match the array
console.log(splitIntoGroups(elements.slice(0, 3), groups));
console.log(splitIntoGroups(elements.slice(0, 5), groups));
console.log(splitIntoGroups(elements.slice(0, 12), groups));
console.log(splitIntoGroups(elements, groups));

// when sum of all groups doesn&#39;t exceed the source array,
// the largest group is repeated until the end of the array
console.log(splitIntoGroups(elements, [1, 3, 5]));

<!-- end snippet -->

答案2

得分: 0

这段代码在您提供的所有输入中都有效并且应该与 ES5 兼容

```js
function groupArray(arr, sizes) {
  if (sizes.length == 0) {
    throw new Error('Sizes array must not be empty')
  }

  var maxSize = Math.max.apply(null, sizes)

  var index = 0
  var output = []
  
  for (var size of sizes) {
    if (index >= arr.length) break

    output.push(arr.slice(index, index + size))
    index += size
  }

  for (var i = index; i < arr.length; i += maxSize) {
    output.push(arr.slice(i, i + maxSize))
  }

  return output
}
英文:

This code worked with all your provided inputs and should be compatible with es5

function groupArray(arr, sizes) {
  if (sizes.length == 0) {
    throw new Error(&#39;Sizes array must not be empty&#39;)
  }

  var maxSize = Math.max.apply(null, sizes)

  var index = 0
  var output = []
  
  for (var size of sizes) {
    if (index &gt;= arr.length) break

    output.push(arr.slice(index, index + size))
    index += size
  }

  for (var i = index; i &lt; arr.length; i += maxSize) {
    output.push(arr.slice(i, i + maxSize))
  }

  return output
}

答案3

得分: 0

以下是翻译好的部分:

"Alright here is the best solution, you were right (almost), instead of using slice you should have used splice to get the right response, you can read about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

The code below is exactly the same as yours but just with the correction. Hope this helps.

var group_size = [1, 3, 5];
var elements = ['a','b','c','d','e','f','g','h','i','j','k','l'];

var output = [];
for (var i=0; i < group_size.length; i++) {
output.push(elements.splice(i, group_size[i]))
}

console.log(output);"

英文:

Alright here is the best solution, you were right (almost), instead of using slice you should have used splice to get the right response, you can read about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

The code below is exactly the same as yours but just with the correction. Hope this helps.

var group_size = [1, 3, 5];
var elements = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;];
    
var output = [];
    for (var i=0; i &lt; group_size.length; i++) {
        output.push(elements.splice(i, group_size[i]))
    }

console.log(output);

答案4

得分: -1

以下是将为您提供所需结果的代码:

const groupSize = [1, 3, 5];
const elements = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'];
const maxGroupSize = Math.max(...groupSize);

let groupIndex = 0;
let startElementIndex = 0;
let output = [];
while (startElementIndex <= elements.length) {
  const currentGroupSize = groupSize[groupIndex] ?? maxGroupSize;
  output.push(elements.slice(startElementIndex, startElementIndex + currentGroupSize));

  startElementIndex += currentGroupSize;
  groupIndex++;
}

步骤:

  1. 确定最大组大小 maxGroupSize
  2. 循环直到在 elements 数组中还有元素
  3. 在每次迭代中,将与当前组大小相对应的元素数量推送到输出中,否则使用来自 maxGroupSize 的值作为组大小
  4. 更新开始索引(startElementIndex)和组索引(groupIndex
英文:

Here is the code that will give you the desired result:

const groupSize = [1, 3, 5];
const elements = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;];
const maxGroupSize = Math.max(...groupSize);

let groupIndex = 0;
let startElementIndex = 0;
let output = [];
while (startElementIndex &lt;= elements.length) {
  const currentGroupSize = groupSize[groupIndex] ?? maxGroupSize;
  output.push(elements.slice(startElementIndex, startElementIndex + currentGroupSize));

  startElementIndex += currentGroupSize;
  groupIndex++;
}

Steps:

  1. Determine the largest group maxGroupSize
  2. Iterate until there are elements left in the elements array
  3. On each iteration push the number of elements that corresponds to the current group size, otherwise use the value from maxGroupSize as a group size
  4. Update indexes for the start index(startElementIndex) and the group index(groupIndex)

答案5

得分: -1

使用while循环,并在超出边界时使用最大组大小

var group_size = [1, 3, 5];
var elements = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", 'm', 'n', 'o', 'p'];

const max_size = Math.max(...group_size);
const output = [];
let last = 0;
let i = 0;

while (last < elements.length) {
  output.push(elements.slice(last, last += (group_size[i] ?? max_size)));
  i++;
}
console.log(output);
英文:

Use while loop and using max group size when groups out of bounds

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var group_size = [1, 3, 5];
var elements = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;, &quot;i&quot;, &quot;j&quot;, &quot;k&quot;, &quot;l&quot;,&#39;m&#39;,&#39;n&#39;,&#39;o&#39;,&#39;p&#39;];

const max_size = Math.max(...group_size);
const output = [];
let last = 0;
let i = 0;

while (last &lt; elements.length) {
  output.push(elements.slice(last, last += (group_size[i] ?? max_size)));
  i++;
}
console.log(output);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月13日 00:37:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定