- var class1 = [75, 53, 92, 100, 24, 55, 86,
- 85, 43, 8, 84, 82, 100, 51];
- var class2 = [54, 92, 9, 65, 66,
- 83, 44, 81, 88, 100];
- function compareNumbers(a, b) {
- return a - b;
- }
- function compareNumbers2(a, b) {
- return b - a;
- }
- console.log('Before sorting');
- console.log(class1);
- console.log(class2);
- class1.sort(compareNumbers);
- class2.sort(compareNumbers2);
- console.log('\nAfter sorting');
- console.log(class1);
- 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