How to sort an array of integers correctly in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

To sort an array of integers, use sort() in JavaScript.

Example

Following is the code −

var arrayOfIntegers = [67, 45, 98, 52];
arrayOfIntegers.sort(function (first, second) {
   return first - second;
});
console.log(arrayOfIntegers);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo310.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo310.js
[ 45, 52, 67, 98 ]
raja
Published on 26-Oct-2020 15:31:55
Advertisements