3

Let's say I have an array = [0,1,2,3,4,5,6] and I want to "partition" it into 3 arrays, based on reminder after division by 3.

so basically I'd want something like:

_.my_partition([0,1,2,3,4,5,6], function(item) {return item % 3;})
// [[0,3,6], [1,4],[2,5]]

(I can use lodash, underscore, if ti helps...)

Novellizator
  • 13,633
  • 9
  • 43
  • 65

1 Answers1

7

There are multiple to do this:

I. Normal function

function partition(items, n) {
    var result = _.groupBy(items, function(item, i) {
        return Math.floor(i % n);
    });
    return _.values(result);
}

myArray = [1,2,3,4,5,6,7,8,9,10];
partition(myArray, 3);

II. Adding a prototype method

Array.prototype.partition = function(n) {
    var result = _.groupBy(this, function(item, i) {
        return Math.floor(i % n);
    });
    return _.values(result);
}

myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.partition(3)

Create an _.partitionToGroups method

_.partitionToGroups = function(items, n) {
    var result = _.groupBy(items, function(item, i) {
        return Math.floor(i % n);
    });
    return _.values(result);
}

myArray = [1,2,3,4,5,6,7,8,9,10];
_.partitionToGroups(myArray, 3);
Joshua Arvin Lat
  • 1,029
  • 9
  • 8
  • Be careful with the third approach, lodash already has a [partition()](https://lodash.com/docs#partition) function. – Adam Boduch Apr 09 '15 at 13:42
  • Thanks for this @AdamBoduch . Let's rename it to partitionToGroups – Joshua Arvin Lat Apr 09 '15 at 13:47
  • 1
    In lodash 4, the index argument was removed from the `groupBy` callback, so you need to keep track of it on your own. – Ethan C Sep 08 '16 at 17:42
  • 3
    first "normal function" does nothing to split them. I copy-paste the code to the console and it outputs an Array of 10 items inside another array :/ – vsync Oct 20 '16 at 22:47