I have the below function that separates one array into chunks of arrays but I can't loop through each one alone, I always get the result for the for loop as undefined
function splitArrayIntoChunksOfLen(arr, len) {
var chunks = [], i = 0, n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, i += len));
}
return chunks;
}
var alphabet=['a','b','c','d','e','f'];
var alphabetPairs=splitArrayIntoChunksOfLen(alphabet,2); //split into chunks of two
console.log(alphabetPairs);
// the problem is in the below for loop
for (let x = 0; x < alphabetPairs.length, x++;) {
console.log(x);
}
the split function gives a result as follow:
0: Array [ "a", "b" ]
1: Array [ "c", "d" ]
2: Array [ "e", "f" ]
length: 3
now I want to loop through each array of these and do a specific action until all the arrays end but don't know what am I missing?
Will appreciate your kind help.
Thank you
I used the below for loops and it worked for me
for (let z = 0; z < lines.length; z++) {
for (let j = 0; j < lines[z].length; j++) {
}
}
You have to use callback functions.So the problem is that the loop written to pirnt the alphabetPairs array compiles sooner than the alphabetPairs generation. You can use callback functions to solve the problems.
function splitArrayIntoChunksOfLen(arr,myFunc, len) {
var chunks = [], i = 0, n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, i += len));
}
myFunc(chunks)
}
const printingHandler=(myNewArray)=>{
console.log(myNewArray)
}
var alphabet=['a','b','c','d','e','f'];
splitArrayIntoChunksOfLen(alphabet,printingHandler,2); //split into chunks of two