0

This is kind of confusing so I will just demonstrate. I would like to create a function that takes an array like this:

[1, 2, 3, 4, 5, 6, 7]

...and returns an array of arrays like this:

[[1, 5], [2, 6], [3, 7], [4]]

assuming that the user wanted 4 groups. Notice that the elements are added to each group before 5th element is added back to the first.

Is there a simple way to do this? My project is using webpack, so I am open to ES6+ or even lodash. Thanks!

4
  • Please also explain what you are trying to do, what happens if the array has an even number of elements? Commented May 28, 2018 at 20:22
  • And what's the pattern? I mean, why it's 1 with 5 and not 1 with 6? Commented May 28, 2018 at 20:23
  • @Luca Well, I am rearranging an array of DOM elements but I thought the number examples was simpler. If perhaps there were 10 elements and 4 groups, it would look like [[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]] Commented May 28, 2018 at 20:24
  • @MitcaVicentiu There are 4 groups, and so 1 through 4 go in the first groups, and then 5 starts back at the very first, six to the second, and so on. Commented May 28, 2018 at 20:26

1 Answer 1

3

My proposal is:

var numGroups= 4;
var result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(function(acc, ele, idx) {
    var i = idx % numGroups;
    (acc[i] == undefined) ?  acc[i] = [ele] : acc[i].push(ele);
    return acc;
}, []);

console.log(result);

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

1 Comment

Perfect! Thank you so much! If you wouldn't mind, could you just give a very brief explanation?

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.