CodeBox CodeBox

JavaScript chunk [more practice]

Typescript / JS

1. 🧐 Expected Output

--- Examples
chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]


2. 🤔 My Solution

function chunk(array, size) {
  const result = [];
  const _array = [...array];
  const length = [...array].length;

  if (length <= size) {
    result.push(array);
  } else {
    for (let index = 1; index <= _array.length / size; index++) {
      const pickedElements = array.splice(0, size);
      result.push(pickedElements);
    }

    if (length % size !== 0) {
      result.push(array);
    }
  }
  return result;
}


3. 🎊 Best Solution

function chunk(array, size) {
  const chunked = [];
  let index = 0;

  while (index < array.length) {
    chunked.push(array.slice(index, index + size));
    index += size;
  }

  return chunked;
}