Home > Software engineering >  Split array into chunks in js ignore first element if exist and never leave 1 element alone
Split array into chunks in js ignore first element if exist and never leave 1 element alone

Time:10-27

I want to split an array to sets of 2, having teachers in own chunk if it exist and never have a single item chunk at the end.

const perChunk = 2 // items per chunk    

const inputArray = ['teachers', 'art', 'science', 'math', 'language', 'culture']

const result = inputArray.reduce((resultArray, item, index) => { 
  const chunkIndex = Math.floor(index/perChunk)

  if(!resultArray[chunkIndex]) {
    resultArray[chunkIndex] = [] // start a new chunk
  }

  resultArray[chunkIndex].push(item)

  return resultArray
}, [])

console.log(result);

for example:

['teachers']
['art', 'science']
['math', 'language', 'culture']

CodePudding user response:

I if understand you want to always add teacher in a single chunk at the begging and the rest divide in equal sizes (2 in this case) and if the last element is not matching the desired state will be added to the element before.

I have this approach

const inputArray = ['teachers', 'art', 'science', 'math', 'language', 'culture']

const arrDivider = (arr, perChunk) => {
    const firstElement = "teachers";
    const chunks = [];
    const length = inputArray.length;
    let base = 0;
    let final = perChunk
    // check if teacher exist in the array
    const teacherIndex = arr.indexOf(firstElement);
    if(teacherIndex >= 0){
        chunks.push([arr[teacherIndex]]) // push it to chunkjs
        arr.splice(teacherIndex, 1) // removing teacher from the array
    }

    for (let i = 0; i < Math.ceil(length / perChunk); i  ) {
        chunks.push(arr.slice(base, final));
        base = final;
        final = final   perChunk
    }
    // If the last item has more than "perChunk" add it to the item before
    const lastItem = chunks[chunks.length - 1]
    if (lastItem.length != perChunk) {
        // If the last element is not the desired size add elements to the element before 
        chunks[chunks.length - 2].push(...lastItem)
        chunks.pop(); // now last item is removed
    }
    return chunks;
}

const chunks = arrDivider(inputArray, 2)
console.log(chunks)

CodePudding user response:

Check this:

// Define params.
const perChunk = 2;
const firstChunkWords = ['teachers'];
const inputArray = ['teachers', 'art', 'science', 'math', 'language', 'culture'];

// Calc first chunk.
const firstChunk = inputArray.filter(item => firstChunkWords.includes(item));

// Calc other chunks.
const inputArrayWithoutFirstChunkWords = inputArray.filter(item => !firstChunkWords.includes(item));
const otherChunks = inputArrayWithoutFirstChunkWords.reduce((resultArray, item, index) => {
  const chunkIndex = Math.floor(index / perChunk);

  if (!resultArray[chunkIndex]) {
    if (index === inputArrayWithoutFirstChunkWords.length - 1) {
      resultArray[chunkIndex - 1].push(item);
      return resultArray;
    }
    resultArray[chunkIndex] = [];
  }

  resultArray[chunkIndex].push(item);

  return resultArray;
}, []);

// Concat chunks.
const result = [firstChunk, ...otherChunks];

// Show result.
console.log(result);

  • Related