In case that there is a bi-dimensional array which is iterated using for...of
, how is the best way to skip the last element?
For example, having an array arr
, the normal approach would be:
for(const subArray of arr) { ... }
to skip the last element it could be used before the loop: arr.slice(0, -1);
which works fine but it removes that data which should be avoided.
Is there a way to make it skip the last element without losing data?
slice()
does not change the array, but returns a new array (unlike splice()
, which does mutate the array), therefore it is safe to use:
for (const subArray of arr.slice(0, -1)) { ... }