Reputation: 123
I have no idea how you call the following, but I need a sort of pattern within my loop.
Let's assume I have 2 arrays.
Array1 = 1..10
Array2 = ['a','b','a','b','b']
The outcome I need should be:
1a,
2b,
3a,
4b,
5b,
6a,
7b,
8a,
9b,
10b
How do I achieve this with a Twig template?
Upvotes: 2
Views: 356
Reputation: 186688
You can try using modulo arithmetics, e.g. (C# code):
// result array will be max of Array1 and Array2 lengths
string[] Array3 = new string[Math.Max(Array1.Length, Array2.Length)];
// Note Array1[i % Array1.Length] and Array2[i % Array2.Length]
// index of each array (Array1, Array2) is remainder of Array1.Length or Array2.Length
// So i % Array1.Length will be 0, 1, ..., Array1.Length, 0, 1, 2 etc
for (int i = 0; i < Array3.Length; ++i)
Array3[i] = $"{Array1[i % Array1.Length]}{Array2[i % Array2.Length]}";
// Let's have a look at Array3:
Console.Write(string.Join(", ", Array3));
Upvotes: 1
Reputation: 28414
Using modulo
in JavaScript
:
const _getArr = (from, to, chars) => {
const res = [];
const len = chars.length;
let count = 0;
for (let i = from; i <= to; i++) {
console.log(count, count%len, chars[count % len]);
res[count] = `${i}${chars[count % len]}`;
count++;
}
return res;
}
console.log( _getArr(1, 10, ['a','b','a','b','b']) );
Upvotes: 1