Thursday, November 18, 2021

JAVASCRIPT - How to sort an array

// ancending order
    
var numbers = [ 10, 12, 5, 7.5, 7 ];
numbers.sort( ( a, b ) => a - b );
numbers.forEach( item => {
  document.write( item + "
" ); }); document.write( "
" ); // descending order numbers.sort( ( a, b ) => b - a ); numbers.forEach( item => { document.write( item + "
" ); });
Output:
5
7
7.5
10
12

12
10
7.5
7
5

No comments:

Post a Comment