How to make a loop that continues from the end of the index of an ended for loop?

Viewed 55

I need to make manually a csv string. To do this, I have 2 arrays one for the headers and one for the data. I almost tried everything and most cases I run into a never ending loop.

    function addDataLineToCsv(headers, data, index) {
       var returnString = ""
       for (index; index <= headers.length; index++) {
           returnString += data[index]
       }
    }

The problem here is that I have a specified number of headers. But in the array 'data' I have all the data ordered by the headers. For example:

var headers =' ['ID', 'name', 'age'] 


then the array of data looks like this:

var data = ['ID(data)', 'name(data)', 'age(data)', 'ID(data)', 'name(data)', 'age(data)'....]

What i want to do is sort of looping through the array 'data', but always with the count of the headers so that I get a sort of "group" effect, where I can add lines to a string like:

ID,name,age
 0, John, 25
 1, Jane, 23

Thak you for the help and excuse me if I formed the question a little bit messy.
1 Answers

Your group_item_count would be your headers.length.

let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

let group_item_count = 4;
let data_length = data.length

for(let i = 0; i < data_length; i += group_item_count){
  let offset = group_item_count;
  if(i + offset > data_length) {
    offset = data_length % group_item_count;
  }
  let group = data.slice(i, i + offset)
  console.log(group)
}

You can essentially use this code to iterate over a flat array in "group"s (each "group"'s length being group_item_count). As you can see if the data.length is not divisible by group_item_count without a remainder, the last "group"'s length would be the remainder of the division.

Related