Home > Net >  Group arrays into a set of 1 and n in javascript
Group arrays into a set of 1 and n in javascript

Time:10-07

I'm making a photo book where I expect all odd pages to contain exactly one image and even pages to contain four images, so far here is my solution:

      let images = [{src: ''}, ...]
      let imageGroups = [];
      let group = [];
      images.forEach((image, i) => {
        group.push(image);
        if (group.length === 1 && i % 2 === 0) {
          imageGroups.push(group);
          group = [];
        } else if (i % 2 && group.length >= 3) {
          imageGroups.push(group);
          group = [];
        }
      });
      if (group.length) {
        imageGroups.push(group);
      }

The probelm with this though is that, the grouping for even pages works well when I compare the group.length with an even value, (i % 2 && group.length >= 3) will put 3 items in a group, (i % 2 && group.length >= 5) will put 5 items in a group but when I do (i % 2 && group.length >= 4) everything just goes kabloey.

CodePudding user response:

Here's a solution according to my comment. Hope it helps.

let images = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
let imageGroups = [[]];

// even page 1 item, odd page 4 items, you may change this on your will
const batches = [1, 4];

// get the last group from imageGroups
let lastGroup = imageGroups[imageGroups.length - 1];

images.forEach(image => {
    // if the last group is full, create a new group and push it into imageGroups
    if (lastGroup.length >= batches[(imageGroups.length - 1) % batches.length]) {
        lastGroup = [];
        imageGroups.push(lastGroup);
    }

    lastGroup.push(image);
});

console.log(imageGroups);

  • Related