-1

Hi i want to split an array by some given count.

arr = [0,1,2,3,4,5,6,7,8,9,10]
$scope.arraySpliter(arr);
$scope.arraySpliter = function (a) {
        var arrays = [], size = 3;
        var tempCount = Math.ceil(a.length / 3);

        while (a.length > 0)
            arrays.push(a.splice(0, tempCount));

        console.log(arrays);
    };

I want split array like this. [0,1,2,3][4,5,6,7][8,9,10]

Mahesh Sanjeewa
  • 217
  • 2
  • 11
  • 1
    Hi! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Oct 03 '18 at 17:41
  • 1
    Also, your split is into 5-element array, 4-element array and 3-element array. Can you explain what this logic is? (and what you mean by "static count", because we're clearly using words differently) – Amadan Oct 03 '18 at 17:42
  • 1
    Also, `4` ends up in both the first and second array? – CRice Oct 03 '18 at 17:44
  • 1
    Related: [Splitting a JS array into N arrays](https://stackoverflow.com/questions/8188548/splitting-a-js-array-into-n-arrays) – CRice Oct 03 '18 at 17:52
  • Hi, i want to split this array as dividing by given count. as example if i set dividing count as 3, the result should be 3 new arrays. – Mahesh Sanjeewa Oct 03 '18 at 17:52

1 Answers1

1

Here is a recursive approach:

const splitIn = count => arr => {
  if (count < 2) {return [arr]}
  const first = Math.ceil(arr.length  / count);
  return [arr.slice(0, first)].concat(splitIn(count - 1)(arr.slice(first)))
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log(splitIn(3)(arr))

This yields the first four (ceiling(10 / 3)) elements as its first group and then recursively splits the remaining six into two groups. When we get down to splitting into a single group, it simply wraps it in an array.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103