编写一个函数,将数组(第一个参数)拆分为大小的长度(第二个参数),并将它们作为多维数组返回

时间:2015-05-31 18:40:16

标签: javascript

我正在处理一个javascript问题,要求我:

编写一个将数组(第一个参数)拆分为大小长度(第二个参数)的函数,并将它们作为多维数组返回。

例如,输入

chunk([0, 1, 2, 3, 4, 5], 2)

应该返回' chunked arrays': [[0,1],[2,3],[4,5]]

我可以让它适用于大多数示例,但是当有超过2个块时,它会切换顺序,我不知道为什么。这是我写的代码:

function chunk(arr, size) {
  var newArray = [],
      i, temp = arr;
  for (i = 0;i<= arr.length-size;i+=size){
    newArray.push(arr.slice(i,i+size));
    temp.splice(i,size);
  }
  newArray.push(temp);
  return newArray;
}
chunk(['a', 'b', 'c', 'd'], 2);

9 个答案:

答案 0 :(得分:7)

另一个版本:

function chunk(arr, size) {
    var result = [];
    while (arr.length > size) {
        result.push(arr.splice(0, size))
    }
    if (arr.length)
        result.push(arr);

    return result;
}

答案 1 :(得分:2)

function chunk(arr, size) {
  var newArr = []; // New empty array
  while (arr.length > 0) { // Loop thru the array items
    newArr.push(arr.splice(0, size)); // Removes first 2 items then add it to new array
  }
  return newArr; // New 2D array
}

我尝试在控制台中使用这些代码行,它工作得很好。

答案 2 :(得分:1)

问题是,您在每次迭代时都i前进size,并从位置size中移除i个元素。这会导致您跳过处理每个其他块。此外,您的继续条件应为i < arr.length-size;实际上,在循环退出之后推送它之前,您需要测试一个空的temp。尝试将循环重写为:

for (i = 0; i < arr.length-size;){
    newArray.push(arr.slice(i,i+size));
    temp.splice(i,size);
}

由于i始终为0,因此循环可以简化为:

while (arr.length > size) {
    newArray.push(arr.slice(0,size));
    temp.splice(0,size);
}

答案 3 :(得分:0)

function chunk(arr, size) {
  var newArr = [];
  // x is less than or equals arr.length.
  for(var x = 0; x <= arr.length; x++){
     newArr.push(arr.splice(0, size));
  }

  if (arr.length){
     newArr.push(arr);
  }
  return newArr;
}

chunk(['a', 'b', 'c', 'd'], 2);

答案 4 :(得分:0)

$('.user_edit').validate({

    onkeyup: false,
    errorClass: 'has-error-text',
    validClass: 'valid',
    rules: {
        "data[PersonMaster][first_name]": {
            required: true
        },
        "data[PersonMaster][last_name]": {
            required: true
        },
        "data[PersonMaster][email_address]": {
            required: true,
            email: true
        },
        "data[PersonMaster][mobile_number_code]": {
            required: true
        },
        "data[PersonMaster][mobile_number]": {
            required: true
        },
        "data[PersonMaster][country_id]": {
            required: true
        }
    },
    messages: {
        "data[PersonMaster][first_name]": {
            required: globalValidations.Modules.addUser.first_name
        },
        "data[PersonMaster][last_name]": {
            required: globalValidations.Modules.addUser.last_name
        },
        "data[PersonMaster][email_address]": {
            required: globalValidations.Modules.addUser.email_address,
            email:globalValidations.Modules.addUser.email_valid
        },
        "data[PersonMaster][mobile_number_code]": {
            required: globalValidations.Modules.addUser.mobile_number_code
        },
        "data[PersonMaster][mobile_number]": {
            required: globalValidations.Modules.addUser.mobile_number
        },
        "data[PersonMaster][country_id]": {
            required: globalValidations.Modules.addUser.country_code
        }
    },
    highlight: function(element) {
        alert("hi");

        $(element).closest('div').addClass("has-error");
    },
    unhighlight: function(element) {

        $(element).closest('div').removeClass("has-error");
    },
    errorPlacement: function(error, element) {

        $(element).closest('div').append(error);
    },
    submitHandler: function(form) {


        $("#loading_main").show();
        var data = $(form).serialize();
         var page_number = $("#page_value").val();

        $.ajax({
            url: site_url + "user_masters/edit_action",
            data: data,
            type: "POST",
            success: function(response) {

                $("#loading_main").hide();
                var response_object = jQuery.parseJSON(response);
                if (response_object.error_code == 0) {
                     UserloadPiece(site_url + "user_masters/user_list/" + (new Date()).getTime() + '/page:' + page_number + '', ".user-content-table-inner", '');
                //                        setTimeout(message_hide("alert", "", "alert-success"), 5000);
                } else if (response_object.error_code == '1') {
                    $("#alert-edit-profile").show();
                    $("#alert-edit-profile").removeClass("alert-success");
                    $("#alert-edit-profile").addClass("alert-danger");
                    $("#alert-edit-profile").html(response_object.message);
                } else if (response_object.error_code == '2') {
                    var i = 0;
                    $.each(response_object.message, function(field, error) {
                        if (field != "null") {
                            $(".has-error-text").empty();

                            $("#" + field + "_validation").closest('div').addClass("has-error");
                            $("#" + field + "_validation").text(error);
                            $("#" + field + "_validation").show();
                            if (i == 0)
                                $("#" + field).focus();
                            i = i + 1;
                        }
                    });
                }
                else if(response_object.error_code == '9'){
                    handle_redirect();
                }
            }
        });
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert("There is some error while processing your request. please try again later.");
        window.location.href = site_url + 'user_masters/login';
    }
});

答案 5 :(得分:0)

这是我的解决方案:

function chunkArrayInGroups(arr, size) {
  var acum=[];
  for(i=0;i<arr.length;i=i+size)
  {
    var vec=arr.slice(i,size+i);
    acum.push(vec);
  }

  return acum;
}

答案 6 :(得分:0)

这么多方法......

function chunkArrayInGroups(arr, size) {
 var value = [];

for(var i =0; i<arr.length; i += size){
 value.push(arr.slice(i, size+i));
}

return value;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

答案 7 :(得分:0)

function chunkArrayInGroups(arr, size) {
  var result = [],
      iterations = Math.ceil(arr.length/size);
  for (var i =0; i<iterations;i++){
      var sub = arr.splice(0, size);
      result.push(sub);
  }
  return result;       
}

答案 8 :(得分:0)

    function chunkArrayInGroups(arr, size) {

  var temp = [];
  var result = [];

  for (var a = 0; a < arr.length; a++) {
    if (a % size !== size - 1)
      temp.push(arr[a]);
    else {
      temp.push(arr[a]);
      result.push(temp);
      temp = [];
    }
  }

  if (temp.length !== 0)
    result.push(temp);
  return result;
}