Reputation: 6316
I am trying to find out why I am not able to get the single values of each array of items individually every 3 seconds.
As you can see I am getting entire array values instead of getting them individually. What I need it to get then individually and console log of ending each level of first level array
var imgs = [
[
['#fff', '#eee'],
['#117A65', '#E74C3C'],
['#F39C12', '#AF7AC5']
],
[
['#7B241C ', '#eee'],
['#117A65', '#909497 ']
],
[
['#17A589', '#626567']
],
[
['#5499C7', '#eee'],
['#117A65', '#884EA0']
],
];
for (let i = 0; i < imgs.length; i++) {
for (let j = 0; j < imgs[i].length; j++) {
for (let b = 0; b < imgs[j].length; b++) {
(function(index) {
setTimeout(function() {
console.log(imgs[i][j][b]);
}, i * 3000);
})(i);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: 1
Views: 33
Reputation: 44145
Just flat
the array and use one loop:
var imgs=[[['#fff','#eee'],['#117A65','#E74C3C'],['#F39C12','#AF7AC5']],[['#7B241C ','#eee'],['#117A65','#909497 ']],[['#17A589','#626567']],[['#5499C7','#eee'],['#117A65','#884EA0']]];
const flattened = imgs.flat(2);
for (let i = 0; i < flattened.length; i++) {
console.log(flattened[i]);
}
.as-console-wrapper { max-height: 100% !important; top: auto; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you need to do something after each first-level iteration, you should go with a classic for
loop:
var imgs=[[['#fff','#eee'],['#117A65','#E74C3C'],['#F39C12','#AF7AC5']],[['#7B241C ','#eee'],['#117A65','#909497 ']],[['#17A589','#626567']],[['#5499C7','#eee'],['#117A65','#884EA0']]];
for (let i = 0; i < imgs.length; i++) {
for (let j = 0; j < imgs[i].length; j++) {
for (let k = 0; k < imgs[i][j].length; k++) {
console.log(imgs[i][j][k]);
}
}
console.log("First level iteration complete - callback here!");
}
.as-console-wrapper { max-height: 100% !important; top: auto; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: 3