Aim of the puzzle: Use a classic for loop to access every 3rd element in an array.
Walk through of solution: The tacos
array is imported from additional code. It is shuffled before every code run, so the array should have a different order of elements each time.
The classic for loop declares the looping variable i
and sets its value to 0. After each iteration, the operation i += 3
will update i
by 3
. The iteration will continue as long as i < tacos.length
is true
.
Inside the code block, we can access and print out the current element in the tacos
array by using i
for its index.
Sample code solution:
import { tacos } from 'grasshopper.taqueria';
for (let i = 0; i < tacos.length; i += 3) {
console.log(tacos[i]);
}
Javascript Concepts: Classic For Loops, Addition Assignment Operators, Imports
Additional Code (hidden code that runs before the puzzle’s code):
let _tacos = [
'al pastor',
'carnitas',
'lengua',
'pollo',
'carne asada',
'tripas',
'chorizo',
'barbacoa',
'arroz con frijoles'
];
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
let tacos = shuffle(_tacos);