Search code examples
javascriptarraysdivide

How to prepared array based on dividable value from length of people array?


Below is an array of people IDs

var arrPeopleIDs = [1,2,3,4,5];

I'd like to separate it into groups of N or less starting from the end of array.

people: 5
divide: single/double (N = 2)

  • 1 key for single with 1
  • 1 key for double with 2,3
  • 1 key for double with 4,5
// Below output expected
var arrResult = [
 [1], [2,3], [4,5]
];

people: 5
divide: single/double/triple (N = 3)

  • 1 key for double with 1,2
  • 1 key for triple with 3,4,5
// Below output expected
var arrResult = [
 [1,2], [3,4,5]
];

people: 5
divide: single/double/triple/quad (N = 4)

  • 1 key for single with 1
  • 1 key for quad with 2,3,4,5
// Below output expected
var arrResult = [
 [1], [2,3,4,5]
];

Can someone please help me with the expected output?

Thanking you in advance!


Solution

  • There will only ever be one remainder while chunking like this, so you can safely chunk the array, then add the remainder, if there is any:

    var arrPeopleIDs = [1, 2, 3, 4, 5, 6];
    
    const chunk = (arr, d) => {
      const temp = arr.slice()
      const out = []
      const rem = temp.length % d
    
      while (temp.length !== rem) out.unshift(temp.splice(temp.length - d, d))
      rem && out.unshift(temp.splice(0, rem))
    
      return out
    }
    
    console.log(chunk(arrPeopleIDs, 1))
    console.log(chunk(arrPeopleIDs, 2))
    console.log(chunk(arrPeopleIDs, 3))
    console.log(chunk(arrPeopleIDs, 4))
    console.log(chunk(arrPeopleIDs, 5))

    Above, is a function that will take an array, and a number - which is the max size of the chunk - and return a chunked array, starting with biggest chunks from the end of the array, then the remainder at the start. This function will not modify the original array - so it can be called multiple times