简体   繁体   English

如何将数组分成两半,直到达到一定大小的块?

[英]How to split an array in half until chunks of a certain size are reached?

I have an array with a variable length that is greater than 3 and can be odd or even. 我有一个可变长度大于3的数组,可以是奇数或偶数。

For example: var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; 例如: var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

Now I want to split that array into halves. 现在,我想将该数组分成两半。

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

Next I want to split those chunks into halves and to keep doing that until the chunks have a length of 3 or 2. 接下来,我想将这些块分割成两半,并继续这样做,直到块的长度为3或2。

Finally I want to store those chunks in a new array. 最后,我想将这些块存储在新数组中。

var newarr = [['a','b','c'],['d','e'],['f','g','h'],['i','j']];

How would I do this? 我该怎么做?

A self-suggesting way to do this is to use a recursive function F: for an input array arr if its length is <= 3 then the result is [arr] , otherwise it is F(first_half_of_arr) concatenated with F(second_half_of_arr) . 一种自暗示的方式来做到这一点是利用一个递归函数F:用于将输入阵列arr如果其长度为<= 3则结果为[arr]否则是F(first_half_of_arr)与级联F(second_half_of_arr)

In code this translates to: 在代码中,它转换为:

function recursiveSplit(arr) { 
    return arr.length <= 3 ? [arr] : 
        recursiveSplit(arr.slice(0, Math.ceil(arr.length / 2)))
        .concat(recursiveSplit(arr.slice(Math.ceil(arr.length / 2))));
}

You can exclude the Math.ceil calls, but if you do you are going to get the 2-length chunks before the 3-length ones in your result. 您可以排除Math.ceil调用,但是如果这样做,您将在结果中获得3个长度的块之前得到2个长度的块。

Now in practice an iterative implementation should be much more performant than a recursive one because it won't need to create and abandon small arrays entirely, so if this is expected to operate on large arrays you should probably stay away from recursion. 现在, 在实践中 ,迭代实现应该比递归实现更具性能,因为它不需要完全创建和放弃小的数组,因此,如果期望这种方法可以在大数组上运行,则您可能应该避免递归。

var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var arr1 = arr.splice(0, Math.ceil(arr.length / 2));

That will split an array in half, so now arr contain second half of original array and arr1 contains first half. 那将把一个数组分成两半,所以现在arr包含原始数组的后一半,而arr1包含前一半。

You should be able to just repeat in a while loop: 您应该能够在while循环中重复:

while (arr > 3) {
    //continue splicing
}

If you don't think this answer is good enough (It probably makes no sense to anyone other than me, I am so tired right now) please just comment rather than disliking. 如果您认为这个答案不够好(对我以外的任何人来说都没有意义,我现在很累),请发表评论而不是讨厌。

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

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