How to set up an left/right iteration switch

I have an iteration length of 18 that I want to run 4 iterations then switch to 3 times and repeat.

It would look like:
++++
+++
++++
+++
++++
repeat however many iterations in the array length.

I do not really know how to reset the index back to zero on a new line or whatever is required.

You’ll either need a recursive function(a function that calls itself as it works through the array) or a while loop that keeps looping until the values are consumed.

var data = 'abcdefghijklmnop'

var processItems = function(values, i) {
  if (values.length == 0) return values

  console.log(values.slice(0, i))
  return values.slice(i)
}

var processValues = function(values) {
  values = processItems(values, 4)
  values = processItems(values, 3)

  if (values.length > 0) {
    processValues(values)
  }
}

processValues(data)

Can be modified so that it returns an array like ['++++', '+++', '++++'] fairly simply, just need to push things into an array rather that console.logging. slice is a method on strings and arrays so should work if you’re dealing with an arrays too.

1 Like

Here’s another solution

var data = 'abcdefghijklmnop'.split('')

var i = 0;
var count = 4;
var charGroup = []

data.forEach(function(char) {
  charGroup.push(char);
  i++;
  if (i==count) {
    console.log(charGroup);

    count = count == 4 ? 3 : 4;
    i = 0;
    charGroup = [];
  }
})

Thx mark, I can’t use the second solution because it won’t show parts of the array where it is not a perfect 4 or 3. So if the first or last line has only 1 or 2 iterations, it will not be displayed. Your own solution ignores the “o” and “p” at the end. I will need to use the first option without returns.

Again thanks.

Used the while loop based on what you showed me:

var svgArray = 'abcdefghijklmnop'.split(''),
colBloc = 4,
variableBloc = colBloc,
testFire;		
while(svgArray.length > 0) {
	if(variableBloc == colBloc) {
		testFire = svgArray.slice(0, variableBloc);
		svgArray.splice(0, variableBloc);
		if (colBloc - 1 != 0){ // prevent empty arrays
			variableBloc = colBloc - 1;
		};
	} else if(variableBloc == colBloc - 1){
		testFire = svgArray.slice(0, variableBloc);
		svgArray.splice(0, variableBloc);
		variableBloc = colBloc;
	};
	console.log(testFire);
};

Seems to play nice.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.