Home > Web Front-end > JS Tutorial > How to Sort an Array of Integers Numerically in JavaScript?

How to Sort an Array of Integers Numerically in JavaScript?

Barbara Streisand
Release: 2024-12-27 02:59:16
Original
259 people have browsed it

How to Sort an Array of Integers Numerically in JavaScript?

Sorting an Array of Integers Numerically

Sorting an array of integers numerically can be a challenge when the default sorting method treats them as strings. In this situation, the sort function sorts the values alphabetically, resulting in an incorrect numerical ordering.

To overcome this, a custom sorting function can be implemented to handle numeric sorts explicitly. The sortNumber function sorts elements in ascending order based on their numerical values:

numArray.sort(function(a, b) {
  return a - b;
});
Copy after login

This function subtracts the first element (a) from the second element (b). If a is greater than b, the result will be positive, indicating that a should come after b in the sorted order. If a is less than b, the result will be negative, indicating that a should come before b. If a is equal to b, the result will be zero, indicating that their order should remain unchanged.

By using this custom sorting function, the array of integers will be sorted in ascending numerical order, ignoring the string values:

var numArray = [140000, 104, 99];
numArray.sort(sortNumber);
console.log(numArray); // [99, 104, 140000]
Copy after login

The above is the detailed content of How to Sort an Array of Integers Numerically in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template