How to print array elements in groups of 2 with JavaScript

1 Answer

0 votes
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const len = array.length;

// Group elements by 2 and print
for (let i = 0; i < len; i += 2) {
    const group = array.slice(i, i + 2);
    console.log(group);
}


     
/*
run:
     
[ 1, 2 ]
[ 3, 4 ]
[ 5, 6 ]
[ 7, 8 ]
     
*/

 



answered Jun 21, 2025 by avibootz
...