Computer >> Computer tutorials >  >> Programming >> Javascript

How to sort an array of integers correctly JavaScript?


We are required to write a JavaScript function that takes in an array of Numbers.

The function should then sort the array of numbers in place (either ascending or descending order).

Example

The code for this will be −

const arr = [2, 5, 19, 2, 43, 32, 2, 34, 67, 88, 4, 7];
const sortIntegers = (arr = []) => {
   const sorterAscending = (a, b) => {
      return a - b;
   };
   const sorterDescending = (a, b) => {
      return b - a;
   };
   arr.sort(sorterAscending);
};
sortIntegers(arr);
console.log(arr);

Output

And the output in the console will be −

[
   2, 2, 2, 4, 5,
   7, 19, 32, 34, 43,
   67, 88
]