let dir = "right"; let arr = []; let x = 0; let y = 0; let width = matrix[0].length - 1; let rightcell = 0; let downcell = 0; let lefthell = 0; let topcell = 0; let height = matrix.length - 1; let val; let count=0; let sum=(width+1)*(height+1); while (count<sum) { console.log(dir); switch (dir) { case"right": val = matrix[x][y]; y++; if (y > width - rightcell) { y = width - rightcell; topcell++; x = topcell; dir = "down"; } arr.push(val); break; case"down": val = matrix[x][y]; x++; if (x > height - downcell) { x = height - downcell; rightcell++; y = width - rightcell; dir = "left"; } arr.push(val); break; case"left": val = matrix[x][y]; y--; if (y < 0 + lefthell) { y = 0 + lefthell; downcell++; x = height - downcell; dir = "top"; console.log(x,y); } arr.push(val); break; case"top": val = matrix[x][y]; x--; if (x < 0 + topcell) { x = 0 + topcell; lefthell++; y = lefthell; dir = "right"; } arr.push(val); break;