martes, 30 de septiembre de 2014

How to sort an array of numbers from lowest to highest and highest to lowest

Trying to sort the items in an array that contain only numbers from lowest to highest and from highest to lowest may seem harder than you think but the true is that is very easy if you know how to do it. The problem is that the sort function converts arrays items to strings and for that reason it sorts them alphabetically by comparing character positions in the ASCII table. Then if you sort the array items you can't get the items in the way you want. You need to create a function that tells the sort function how to sort the data. Look at the code below:


  1. var class1 = [75, 53, 92, 100, 24, 55, 86,
  2.               85, 43, 8, 84, 82, 100, 51];
  3.               
  4. var class2 = [54, 92, 9, 65, 66, 
  5.               83, 44, 81, 88, 100];

  6. function compareNumbers(a, b) {
  7.   return a - b;
  8. }

  9. function compareNumbers2(a, b) {
  10.   return b - a;
  11. }

  12. console.log('Before sorting');
  13. console.log(class1);
  14. console.log(class2);

  15. class1.sort(compareNumbers);
  16. class2.sort(compareNumbers2);

  17. console.log('\nAfter sorting');
  18. console.log(class1);
  19. console.log(class2);


function compareNumbers(a, b) {
  return a - b;
}

function compareNumbers2(a, b) {
  return b - a;
}


The first function sorts the items in the array  from lowest to highest and the second function sorts the items in the array from highest to lowest.

As you see it is quite easy to sort the items in the way we want.

You can learn this and more at www.codeavengers.com. The excercise above was taken from Javascript level 2 course.

Español: Cómo ordenar de menor a mayor y de mayor a menor los elementos de un array cuando estos son números.

No hay comentarios:

Publicar un comentario