Syntax error How to sort an array of integers correctly in JavaScript?

How to sort an array of integers correctly in JavaScript?



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 ]
Updated on: 2020-10-26T11:04:21+05:30

380 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements