Search code examples
javascriptobjectfor-loopnested-loops

Javascript: nested for loops to assign values


I have two arrays:

divideArray = [2, 2, 1];

which contains 2+2+1 timeslots

and one containing objects:

starttimeArray = [{starttime: '06:00:00', divideArrayIndex: 0}, {'09:00:00', divideArrayIndex: 0}, {'12:00:00' divideArrayIndex: 0}, {'15:00:00', divideArrayIndex: 0}, {'18:00:00'divideArrayIndex: 0}];

starttimeArray.length is equal to the sum of the elements of divideArray.

Now I want to go through starttimeArray and "assign" every "divideArrayIndex" property to the corresponding index of divideArray like:

{starttime: '06:00:00', divideArrayIndex: 0}
{starttime: '09:00:00', divideArrayIndex: 0}
{starttime: '12:00:00', divideArrayIndex: 1}
{starttime: '15:00:00', divideArrayIndex: 1}
{starttime: '18:00:00', divideArrayIndex: 2}

as divideArray[0] has the value 2 for the first two slots, divideArray[1] is also 2 for the next 2 slots and divideArray[2] (=1) is for the last slot.

I was trying to achieve this using nested for loops, including a while loop, but that is not working and at the moment I absolutely have no clue on how to do it...

 for (starttimeArrayCounter = 0; starttimeArrayCounter < starttimeArray.length;) {
   for (divideArrayCounter = 0; divideArrayCounter < divideArray.length; divideArray++) {
       while (divideArrayCounter < starttimeArray[starttimeArrayCounter]) {
    console.log(starttimeArray[starttimeArrayCounter], divideArrayCounter);
    starttimeArrayCounter++;
    }
  }
}

Thanks in advance.


Solution

  • You can iterate over dividerArray, taking each element as the loop counter while mapping elements from starttimeArray:

    const divideArray = [2, 2, 1];
    const starttimeArray = ['06:00:00', '09:00:00', '12:00:00', '15:00:00', '18:00:00'];
    
    let starttimeIndex = 0;
    let divideIndex = 0;
    for (let loopCounter of divideArray) {
      while (loopCounter > 0) {
        processResult(starttimeIndex, divideIndex);
        starttimeIndex += 1;
        loopCounter -= 1;
      }
      divideIndex += 1;
    }
    
    function processResult(starttimeIndex, divideArrayIndex) {
      console.log({
        starttime: starttimeArray[starttimeIndex],
        divideArrayIndex
      });
    }

    Note: the output is exactly what you've shown in your question, taken as a literal string. It contains the necessary information, feel free to adjust it as needed.