How to sort array of numbers in javascript?

By sorting an array of numbers and using the built-in sort() function, you’ll definitely notice that, by default, sorting doesn’t go from smallest to largest, but alphabetically.

This means, that if we want to sort array: [2 ,8, 200, 6, 803, 4, 3, 440, 7, 44, 71, 65, 32] we receive // [2, 200, 3, 32, 4, 44, 440, 6, 65, 7, 71, 8, 803].

So how can we sort numbers from smallest to largest (or vice versa)? Use simple “trick”:

let arr = [2 ,8, 200, 6, 803, 4, 3, 440, 7, 44, 71, 65, 32];

arr.sort( (a-b) => a-b );      // [2, 3, 4, 6, 7, 8, 32, 44, 65, 71, 200, 440, 803]

arr.sort( (a-b) => b-a );      // [803, 440, 200, 71, 65, 44, 32, 8, 7, 6, 4, 3, 2]

And how to sort multidimensional array?

let arr = [ ['e', 5], ['r', 3], ['!', 7], ['s', 1], ['d', 6] , ['t', 4], ['o', 2] ];

arr.sort( (a-b) => a[1] - b[1] );    // [ ['s', 1],  ['o', 2], ['r', 3], ['t', 4], ['e', 5], ['d', 6], ['!', 7] ]

Joanna

Leave a Reply

Your email address will not be published. Required fields are marked *