1

I'm looking convert an array into an array of subArrays.

An example would be:

let arr = [1, 2, 3, 4, 5, 6, 7, 8]
arr = [[1, 2], [3, 4], [5, 6], [7, 8]]

Now if the length of this array is not divisible by 2

let arr = [1, 2, 3, 4, 5, 6, 7]
arr = [[1, 2], [3, 4], [5, 6], [7]]

My solution to this problem, not very clean IMO

const isPrime = num => {
   for (let i = 2; i < num; i++)
      if (num % i === 0) return false;
    return num > 1;
}
        
const howToGroupArray = (array) => {
    if (array.length === 1) {
        return [1, 0] // group of 1 remainder 0
    }
    else if (!isPrime(array.length) || array.length === 2) {
        return [2, 0] // groups of 2 remainder 0
    }
    else {
        return [2, 1] // groups of 2 and a group of 1
    }

}
        
let values = [1,2,3,4,5,6,7]
let newArray = []
let groups = values.forEach((x, i) => {
    if ((i === 0 || i % 2 === 0) && (i !== (values.length - 1))) {
        newArray.push([x, values[i + 1]])
    }
    else if ((i % 2 === 1) && (i !== (values.length - 1))) {
        null
    }
    else {
        howToGroupArray(values)[1] === 0 ? null : newArray.push([x])
    }
})
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Jack.c
  • 1,035
  • 1
  • 11
  • 14

3 Answers3

3

Ngoc Vuong wrote a nice blog post on chunking arrays. He offers a few solutions in his post, which I've pasted below.

Loop through Array

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunkedArray = chunk(myArray, 2);
console.log(chunkedArray);

function chunk(array, size) {
    const chunkedArray = [];
    for (let i = 0; i < array.length; i++) {
        const last = chunkedArray[chunkedArray.length - 1];
        if (!last || last.length === size) {
            chunkedArray.push([array[i]]);
        } else {
            last.push(array[i]);
        }
    }
    return chunkedArray;
}

Loop through the number of chunks

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunkedArray = chunk(myArray, 2);
console.log(chunkedArray);

function chunk(array, size) {
    const chunkedArray = [];
    const copied = [...array];
    const numOfChild = Math.ceil(copied.length / size);
    for (let i = 0; i < numOfChild; i++) {
        chunkedArray.push(copied.splice(0, size));
    }
    return chunkedArray;
}

Using slice()

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunkedArray = chunk(myArray, 2);
console.log(chunkedArray);

function chunk(array, size) {
    const chunkedArray = [];
    let index = 0;
    while (index < array.length) {
        chunkedArray.push(array.slice(index, size + index));
        index += size;
    }
    return chunkedArray;
}

The recursive method

function chunk(array, size) {
    if (!array) return [];
    const firstChunk = array.slice(0, size); // create the first chunk of the given array
    if (!firstChunk.length) {
        return array; // this is the base case to terminal the recursive
    }
    return [firstChunk].concat(chunk(array.slice(size, array.length), size)); 
}
huwiler
  • 915
  • 9
  • 9
1

Instead of .forEach(), you could use .reduce(), like this:

        
let values = [1,2,3,4,5,6,7]

let newArray = values.reduce((res, x, i, orig) =>
  i%2 ? res : [...res, [x, ...orig.slice(i+1, i+2)]]
, [])

console.log(newArray);

It uses spread syntax to build a result on each even index. The odd indexes merely return the current accumulation.

  • very cool, albeit difficult to digest, solution (for me at least). Wouldn't it be better though to use const instead of let for values and newArray? Nit-picky, I know. – huwiler Jul 07 '20 at 18:44
  • 1
    @huwiler: Yes, `const` would be better. I just used the declarations that the OP included, but I'd definitely prefer `const`. –  Jul 07 '20 at 18:45
0

You could just iterate with an index and increment this by two.

Then take the index for slicing and put the part to the result array.

const
    getGrouped = array => {
        let result = [],
            i = 0;
        
        while (i < array.length) result.push(array.slice(i, i += 2));

        return result;
    };

console.log(getGrouped([1, 2, 3, 4, 5, 6, 7, 8]));
console.log(getGrouped([1, 2, 3, 4, 5, 6, 7]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392