I have a task where I need to slice 3 elements from an array and store them in another array
array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1];
rows = 3;
Here is the method I am using
getVertWallStruct = (array, rows) => {
let i = 1,
storageArr = [],
data = [];
for (let k = 0; k < rows*2; k++) { // everything's ok here
storageArr.push(array.slice(k*rows, (k+1)*rows));
}
data = storageArr;
console.log("storageArr - ", storageArr, " , array - ", array, " , data - ", data);
return data;
}
In this scenario, storageArr is ending up with empty arrays (no data inside). But if I remove the line with data = storageArr; the result is:
storageArr = [ //this is how storageArr should look like in the end
[1, 1, 1],
[0, 1, 1],
[1, 1, 1],
[1, 1, 1],
[0, 1, 1],
[1, 1, 1]
]
Why are the values getting lost?
Update: Even after copying and pasting code from one of the answers, the method is still returning empty data. Why is this happening?
The code snippet looks like:
getVertWallStruct = (array, rows) => {
console.log(array, rows); //looks fine here
let iterator = array.values()
let out = []
for (let i = 0;i < ~~(array.length / rows); i++){
out.push([iterator.next().value, iterator.next().value, iterator.next().value])
}
console.log(out); //why is this empty ???
return out;
}