5

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.

1

6 Answers 6

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)

Sign up to request clarification or add additional context in comments.

Comments

3

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));

2 Comments

This results in [["a","b","c","d"]]
@BviLLe_Kid I had my operands reversed. Give it another shot. (When I'm at a computer I'll turn this into a snippet.)
2

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));

Comments

1

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"]]

1 Comment

You should note that this code will mutate the original array, which may be unexpected behavior.
1

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;
}

2 Comments

While you may have solved this user's problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem.
Thanks for the suggestion. Edited the answer.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.