Learn how to sort a given array in spiral form with JavaScript.

How to format a given array (matrix) in spiral form (snail or clockwise spiral sorting) in JavaScript

Although you won't probably absolutely never use something like this in your Job, because, it doesn't make sense at all, this exercise is very common for homework of young programmers. The idea is simple but the way to achieve not so much, you will have an array that has multiple arrays inside with a square or rectangular shape in the rough sense of the word and the task is to create a function that returns an array with single items that follow the order of a spiral form or well known as a snail as well, for example, analyze the following examples and expected results:

// Example 1.
var matrix1 = [
    [1, 2, 3],
    [4, 5, 6], 
    [7, 8, 9]
]
// Expected = [1, 2, 3, 6, 9, 8, 7, 4, 5]
console.log(some_function(matrix1));

// Example 2.
var matrix2 = [
    [1,  2 , 3,  4,  5 ],
    [6,  7 , 8 , 9,  10], 
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20]
]             
// Expected = [1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12]
console.log(some_function(matrix2));

If you still don't get it, see the graphical explanation in the image of this article, where you can see the arrow following the structured array with the shape of a snail.

Implementation

The given structure will always be a single array with multiple arrays inside, so you can work with it as a quadratic object iterating all over every row and using some flags to return to every row according to the status of the generated array:

/**
 *  Given a matrix of m x n elements (m rows, n columns),
 *  return all elements of the matrix in spiral order.
 *  For example,
 *  Given the following matrix:
 *  [
 *   [ 1, 2, 3 ],
 *   [ 4, 5, 6 ],
 *   [ 7, 8, 9 ]
 *  ]
 *
 *
 *  It should return [1, 2, 3, 6, 9, 8, 7, 4, 5].
 */
function spiral_traversal(array) {
    var result = [];

    if (array.length == 0 ){
        return result;
    }

    var max = array[0].length -1;

    // Grab the first row | result.push.apply(result,array[0])
    for (var i=0;i<=max;i++){
        result.push(array[0][i]);
    }

    // Grab the last column
    for (var i=1;i< max;i++){
        result.push(array[i][max]);
    }

    // Grab the last row
    for (var i=max;i>=0;i--){
        result.push(array[max][i]);
    }

    // Grab the first column
    for (var  i=max-1;i> 0;i--){
        result.push(array[i][0]);
    } 

    subarray = [];
    // Form the inner matrix
    for (var i=1;i<max;i++){
        subarray.push(array[i].splice(1,max-1));
    }

    //call it recursively
    result = result.concat( spiral_traversal(subarray) );

    return result;
}

With this function you will be able to structure the original array with the desired form:

var matrix1 = [
    [1, 2, 3],
    [4, 5, 6], 
    [7, 8, 9]
];

// Prints: [1, 2, 3, 6, 9, 8, 7, 4, 5]
console.log(spiral_traversal(matrix1));

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors