Spiral Traversal of array

Method to traverse an array in a spiral fashion

by Bharat Gupta

JavaScript

var arr = [[1,2,3,4],
 [5,6,7,8],
 [9,10,11,12],
 [13,14,15,16]];
 
 var spiralTraversal = function(matrix) {
 	var result = [];
  var loopAround = function (matrix) {
  	if(matrix.length == 0){
    	return;
    }
    
    // add the first row to result
    result = result.concat(matrix.shift());
    
    // add the last element of each remaining row
    matrix.forEach(function(rightEnd) {
    	result.push(rightEnd.pop());
    });
    
    // add the last row in reverse order
    result = result.concat(matrix.pop().reverse());
    
    // add the first element in each remaining row (going upwards)
    var tmp = [];
    matrix.forEach(function(leftEnd) {
        tmp.push(leftEnd.shift());
    });
    result = result.concat(tmp.reverse());
    
    return loopAround(matrix);
  };
  
  loopAround(matrix);
  return result;
 };
 
 console.log(spiralTraversal(arr));