Languages
[Edit]
EN

JavaScript - sort array of integers

0 points
Created by:
Evania
284

In this article, we would like to show you how to sort array of integers in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let numbers = [10, 2, 5];

numbers.sort((x, y) => {
  return x - y;
});

console.log(numbers);  // 2, 5, 10

 

Practical example

In this example, we use sort() method to sort the array of integers. However, the sort() method sorts elements alphabetically, so we need to specify an additional function inside which handles numeric sorts.

// ONLINE-RUNNER:browser;

let numbers = [10, 2, 5, 1, 3];

numbers.sort((x, y) => {
  return x - y;
});

console.log(numbers);  // 1, 2, 3, 5, 10

Output:

1,2,3,5,10
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join