Back to Web Development
2026-01-057 min read

JS Sort Numeric Array (Web Development)

Learn JS Sort Numeric Array (Web Development) step by step with clear examples and exercises.

Why This Matters

Sorting data is an essential skill for every developer, and understanding how to sort arrays in JavaScript can help you solve real-world problems more efficiently. In this tutorial, we will delve deeper into the topic of sorting a numeric array in JavaScript, discussing its importance, common mistakes to avoid, practice questions to test your understanding, and frequently asked questions.

Why This Matters

Sorting data is crucial for organizing information, making it easier to find specific items or analyze trends. Sorting a numeric array in JavaScript can be useful when dealing with large datasets, such as user scores, product prices, or financial transactions. Understanding how to sort arrays can also help you prepare for interviews and real-world programming challenges.

In addition, mastering the sort() method will equip you with the tools necessary to work on complex data manipulation tasks, making your code more efficient and easier to read.

Prerequisites

To follow this tutorial, you should have a basic understanding of the following topics:

  • Variables and data types in JavaScript
  • Arrays in JavaScript
  • Basic JavaScript syntax (operators, loops, functions)
  • Control structures like if statements and for loops

Core Concept

In JavaScript, arrays are ordered collections of values, and by default, they are sorted in the order they were added (which is not necessarily numeric order). To sort an array numerically, we can use the sort() method.

The sort() method sorts the elements of an array in place and returns the array itself. It takes a comparison function as an argument, which determines the sorting order. If no comparison function is provided, JavaScript uses strict equality (===) to compare values. However, this can lead to unexpected results when sorting numeric arrays because JavaScript converts numbers to strings when comparing them using ===.

To avoid these issues, we can provide a custom comparison function that compares the numerical values directly. Here's an example:

let arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
arr.sort(function(a, b) {
if (a < b) {
return -1; // a comes before b in the sorted array
} else if (a > b) {
return 1; // a comes after b in the sorted array
} else {
return 0; // a and b are equal, so they maintain their original order
}
});
console.log(arr); // Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

In this example, we sort the array arr numerically by comparing the numbers directly using an if-else statement. If the comparison result is negative, the first number comes before the second in the sorted array; if it's positive, the second number comes first. If both numbers are equal, they maintain their original order.

Sorting in descending order

To sort an array in descending order, you can modify the comparison function to return -1 when a is greater than b, and 1 when a is less than b. Here's an example:

let arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
arr.sort(function(a, b) {
if (a > b) {
return -1; // a comes before b in the sorted array (descending order)
} else if (a < b) {
return 1; // a comes after b in the sorted array
} else {
return 0; // a and b are equal, so they maintain their original order
}
});
console.log(arr); // Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1] (sorted in descending order)

Worked Example

Let's work through an example to better understand how sorting a numeric array works in JavaScript:

  1. Create an array of numbers:
let arr = [5, 3, 8, 4, 2];
console.log(arr); // Output: [5, 3, 8, 4, 2]
  1. Sort the array numerically using the sort() method with a custom comparison function:
arr.sort(function(a, b) {
if (a < b) {
return -1; // a comes before b in the sorted array
} else if (a > b) {
return 1; // a comes after b in the sorted array
} else {
return 0; // a and b are equal, so they maintain their original order
}
});
console.log(arr); // Output: [2, 3, 4, 5, 8]

In this example, we sorted the array arr numerically by comparing the numbers directly using an if-else statement. The resulting sorted array is [2, 3, 4, 5, 8].

Sorting in descending order

To sort the same array in descending order, modify the comparison function as follows:

arr.sort(function(a, b) {
if (a > b) {
return -1; // a comes before b in the sorted array (descending order)
} else if (a < b) {
return 1; // a comes after b in the sorted array
} else {
return 0; // a and b are equal, so they maintain their original order
}
});
console.log(arr); // Output: [8, 5, 4, 3, 2] (sorted in descending order)

Common Mistakes

  1. Not providing a custom comparison function: If you don't provide a custom comparison function when sorting a numeric array, JavaScript will convert the numbers to strings and compare them as text, resulting in incorrect sorting order.
let arr = [5, 3, 8, 4, 2];
arr.sort();
console.log(arr); // Output: [2, 3, 4, 5, 8] (incorrectly sorted because of string comparison)
  1. Using the wrong comparison operator: In the custom comparison function, make sure to use - for descending order and + for ascending order. Using the wrong operator will sort the array in the opposite direction you intended.
let arr = [5, 3, 8, 4, 2];
arr.sort(function(a, b) {
return a + b; // This will sort the array in descending order instead of ascending
});
console.log(arr); // Output: [16, 11, 10, 9, 7] (incorrectly sorted because of addition)
  1. Mutating the original array: The sort() method sorts the elements of an array in place. If you need to maintain the original order and return a new sorted array, use the spread operator (...) to create a copy before sorting:
let arr = [5, 3, 8, 4, 2];
let sortedArr = [...arr].sort(function(a, b) {
if (a < b) {
return -1; // a comes before b in the sorted array
} else if (a > b) {
return 1; // a comes after b in the sorted array
} else {
return 0; // a and b are equal, so they maintain their original order
}
});
console.log(arr); // Output: [5, 3, 8, 4, 2] (original array unchanged)
console.log(sortedArr); // Output: [2, 3, 4, 5, 8] (new sorted array)

Common Mistake - Comparing floating-point numbers

When sorting arrays that contain floating-point numbers, you might encounter issues due to JavaScript's floating-point precision limitations. To avoid these issues, it is recommended to convert both numbers to strings and compare them lexicographically (i.e., character by character). Here's an example:

let arr = [3.14, 2.718, 1.618];
arr.sort(function(a, b) {
return a.toString().localeCompare(b.toString());
});
console.log(arr); // Output: [1.618, 2.718, 3.14] (sorted correctly despite floating-point precision issues)

Practice Questions

  1. Write a JavaScript function called sortNumbers() that takes an array of numbers as input and returns the sorted array in ascending order.
function sortNumbers(arr) {
return arr.sort(function(a, b) {
if (a < b) {
return -1; // a comes before b in the sorted array
} else if (a > b) {
return 1; // a comes after b in the sorted array
} else {
return 0; // a and b are equal, so they maintain their original order
}
});
}

let arr = [8, 3, 1, 5, 6];
console.log(sortNumbers(arr)); // Output: [1, 3, 5, 6, 8]
  1. Write a JavaScript function called sortDescending() that takes an array of numbers as input and returns the sorted array in descending order.
function sortDescending(arr) {
return arr.sort(function(a, b) {
if (a > b) {
return -1; // a comes before b in the sorted array (descending order)
} else if (a < b) {
return 1; // a comes after b in the sorted array
} else {
return 0; // a and b are equal, so they maintain their original order
}
});
}

let arr = [8, 3, 1, 5, 6];
console.log(sortDescending(arr)); // Output: [8, 6, 5, 3, 1]
  1. Write a JavaScript function called sortFloatingPointNumbers() that takes an array of floating-point numbers as input and returns the sorted array in ascending order.
function sortFloatingPointNumbers(arr) {
return arr.sort(function(a, b) {
return a.toString().localeCompare(b.toString());
});
}

let arr = [3.14, 2.718, 1.618];
console.log(sortFloatingPointNumbers(arr)); // Output: [1.618, 2.718, 3.14] (sorted correctly despite floating-point precision issues)

FAQ

Q: Why does JavaScript sort numbers as strings by default?

A: JavaScript sorts numbers as strings by default because it uses strict equality (===) to compare values. When comparing two numbers using ===, JavaScript converts them to strings and compares the resulting string representations. This can lead to unexpected results when sorting numeric arrays, so it's important to provide a custom comparison function when sorting such arrays.

Q: Can I sort an array of objects in JavaScript?

A: Yes, you can sort an array of objects in JavaScript by creating a custom comparison function that compares the properties of interest. For example, if you have an array of objects representing users with name and age properties, you can sort the array based on age like this:

let users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
];

users.sort(function(a, b) {
return a.age - b.age;
});
console.log(users); // Output: [ { name: 'Charlie', age: 20 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ] (sorted by age)

Q: Why does sorting floating-point numbers sometimes produce incorrect results?

A: Sorting floating-point numbers can produce incorrect results due to JavaScript's floating-point precision limitations. When comparing two floating-point numbers, the comparison result might not be what you

JS Sort Numeric Array (Web Development) | Web Development | XQA Learn