合并数组的随机元素/拆分成块

时间:2016-09-17 07:12:24

标签: arrays algorithm chunks

如何使用一些特殊算法将数组拆分为块?例如。我需要将数组缩短为10个元素的大小。如果我有11个元素的数组,我想要合并两个下一个常设元素。如果我有13个元素的数组,我想要合并三个元素。等等。有什么解决方案吗?

Sample #1
var test = ['1','2','3','4','5','6','7','8','9','10','11'];
Need result = [['1'],['2'],['3'],['4'],['5|6'],['7'],['8'],['9'],['10'],['11']]

Sample #2
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13'];
Need result = [['1|2'],['3'],['4'],['5'],['6'],['7|8'],['9'],['10'],['11'],['12|13']]

提前谢谢。

3 个答案:

答案 0 :(得分:1)

A - 找出差异并为合并创建如此多的随机数并放入数组中 B - 遍历初始数字数组。
B1 - 如果迭代器编号在合并编号数组中(使用indexOf),则将其与下一个合并并增加迭代器(在合并时已跳过下一个并且已在结果数组中)
B1示例

int mergers[] = [2, 7, 10]
//in loop when i=2
if (mergers.indexOf(i)>-1) { //true
   String newVal = array[i]+"|"+array[i+1]; //will merge 2 and 3 to "2|3"
   i++; //adds 1, so i=3. next loop is with i=4
}

C - 在结果数组中添加新值

答案 1 :(得分:1)

您可以尝试此代码



jQuery(document).ready(function(){ 
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];  


        var arrays = [];

        var checkLength =  test.length;

        var getFirstSet = test.slice(0,10);
        var getOthers = test.slice(10,checkLength);

        $.each( getFirstSet, function( key,value ) {
              if(key in getOthers){
                values = value +'|'+ getOthers[key]; 
                arrays.push(values);
              }else{
                arrays.push(value);            
              }
        });


        console.log(arrays);
  
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

以下代码最有可能实现您的目的。

function condense(a){
  var  source = a.slice(),
          len = a.length,
  excessCount = (len - 10) % 10,
         step = excessCount - 1 ? Math.floor(10/(excessCount-1)) : 0,
    groupSize = Math.floor(len / 10),
     template = Array(10).fill()
                         .map((_,i) => step ? i%step === 0 ? groupSize + 1
                                                           : i === 9 ? groupSize + 1
                                                                     : groupSize
                                            : i === 4 ? groupSize + 1
                                                      : groupSize);
  return template.map(e => source.splice(0,e)
                                 .reduce((p,c) => p + "|" + c));
}

var test1 = ['1','2','3','4','5','6','7','8','9','10','11'],
    test2 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21'];
console.log(condense(test1));
console.log(condense(test2));