最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Slice Array into an array of arrays - Stack Overflow

programmeradmin3浏览0评论

If I have a function:

function sliceArrayIntoGroups(arr, size) {
  var slicedArray = arr.slice(0, size);

  return slicedArray;
}

I am looking to take an array and slice it into an array of arrays.. how would I go about doing so?

So if I had this:

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

The result should be:

[["a","b"],["c","d"]]

But I don't know how to save the second part of the original array after slicing it.

Any help is appreciated.

If I have a function:

function sliceArrayIntoGroups(arr, size) {
  var slicedArray = arr.slice(0, size);

  return slicedArray;
}

I am looking to take an array and slice it into an array of arrays.. how would I go about doing so?

So if I had this:

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

The result should be:

[["a","b"],["c","d"]]

But I don't know how to save the second part of the original array after slicing it.

Any help is appreciated.

Share Improve this question asked Jan 31, 2017 at 18:12 GrizzlyGrizzly 5,9539 gold badges61 silver badges115 bronze badges 1
  • This looks like array chunking and I should remend to you this: locutus.io/php/array/array_chunk – Mike Commented Jan 31, 2017 at 18:20
Add a ment  | 

6 Answers 6

Reset to default 7

The solution using regular while loop and custom step parameter:

function sliceArrayIntoGroups(arr, size) {
  var step = 0, sliceArr = [], len = arr.length;
  while (step < len) {
    sliceArr.push(arr.slice(step, step += size));
  }
  return sliceArr;
}

console.log(sliceArrayIntoGroups(["a", "b", "c", "d"], 2));
console.log(sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 2));
console.log(sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 3));

step option points to an offset of each extraction(slicing)

This ought to do it. It's a simple recursive function that slices n elements from the beginning of the array and calls itself with the remaining elements.

function sliceArrayIntoGroups(arr, size) {
  if (arr.length === 0) { return arr; }
  return [ arr.slice(0, size), ...sliceArrayIntoGroups(arr.slice(size), size) ];
}

console.log(sliceArrayIntoGroups([1,2,3,4,5], 2));
console.log(sliceArrayIntoGroups([1,2,3,4,5], 3));
console.log(sliceArrayIntoGroups([1,2,3,4,5], 10));

try this, it will slice origin array to 2 pieces, then concat to 1 array

function sliceArrayIntoGroups(arr, size) {
  if (size >= arr.length || size <= 0) { return arr; }
  return [arr.slice(0, size), arr.slice(size)];
}
console.log(sliceArrayIntoGroups(["a", "b", "c", "d"], 2));

Try this:

 function sliceArrayIntoGroups(arr, size) {
   var result = [];

   while (arr.length > 0) {
     result.push(arr.splice(0, size));
   }

   return result;
 }


 console.log(sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 3));
 console.log(sliceArrayIntoGroups(["a", "b", "c", "d"], 2));

function sliceArrayIntoGroups(arr, size) {
  var result = [];

  while (arr.length > 0) {
    result.push(arr.splice(0, size));
  }

  return result;
}

This will divide array into pieces where each piece will be the size of size variable, so

sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 3);

will output

[["a", "b", "c"], ["d", "e", "f"]]

Javascript slice() method returns the selected elements in an array, as a new array object. So using for loop create smallArray and push them to arrGroup array.

function sliceArrayIntoGroups(arr, size) {
  let arrGroup =[];
  for (let i=0; i<arr.length; i+=size) {
    let smallArray = arr.slice(i,i+size);//creating smaller array of required size using slice
    arrGroup.push(smallArray);
  }
  return arrGroup;
}

Reduce:

var x = [1,2,3,4,5,6,7,8,9];
var chunk = function(arr,n) {
    var temp;
    return arr.reduce(function(carry,item,index) {

        //if we're at a chunk point: index%n == 0
        if(!(index%n)) { 

            //if temp currently holds items, push it onto carry
            if(temp && temp.length) { carry.push(temp); }

            //reset temp to an empty array
            temp = []; 
        }

        //push the current item onto temp
        temp.push(item);

        //if this is the last item in the array, push temp onto carry
        index == arr.length-1 && carry.push(temp);

        return carry;
    },[]);
};

chunk(x,5);
发布评论

评论列表(0)

  1. 暂无评论