sorting
algorithms
programming
data structures
array manipulation

Sorting result array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Sorting a result array is usually the last step before ranking, pagination, or returning API responses. The logic looks simple, but subtle bugs appear when ties, null values, and mixed key types are not handled explicitly. A robust implementation starts with a clear ordering contract.

Define Sorting Contract First

Before writing comparator code, decide:

  • Primary key and direction.
  • Tie-breaker policy.
  • Null placement policy.
  • Locale rules for text fields.

If these rules are not explicit, different services or clients may produce inconsistent result ordering.

Numeric and Text Sorting in JavaScript

Default JavaScript sort is lexical. Numeric arrays need explicit comparator.

javascript
1const nums = [10, 2, 30, 4];
2nums.sort((a, b) => a - b);
3console.log(nums);
4
5const words = ["pear", "Apple", "banana"];
6words.sort((a, b) => a.localeCompare(b));
7console.log(words);

Without a numeric comparator, 10 can sort before 2 unexpectedly.

Sorting Array of Objects

Most result arrays are objects. Build comparator chains with clear tie rules.

javascript
1const rows = [
2  { id: 1, score: 88, name: "Ava" },
3  { id: 2, score: 92, name: "Leo" },
4  { id: 3, score: 92, name: "Mia" }
5];
6
7rows.sort((a, b) => {
8  if (a.score !== b.score) return b.score - a.score;
9  return a.name.localeCompare(b.name);
10});
11
12console.log(rows);

Add a unique final tie-breaker such as id for strict deterministic output.

Null and Undefined Handling

Missing values need explicit behavior or ordering can vary unexpectedly.

javascript
1const data = [3, null, 1, undefined, 2];
2
3data.sort((a, b) => {
4  const ax = a ?? Number.POSITIVE_INFINITY;
5  const bx = b ?? Number.POSITIVE_INFINITY;
6  return ax - bx;
7});
8
9console.log(data);

This policy pushes null-like entries to the end in ascending order.

Stable Pagination and API Responses

If sorted output feeds pagination, unstable ties can make items jump between pages. Ensure deterministic comparator chains:

javascript
1rows.sort((a, b) => {
2  if (a.score !== b.score) return b.score - a.score;
3  return a.id - b.id;
4});

Deterministic sorting is essential for consistent page tokens and repeatable client behavior.

Immutable Versus In-Place Sorting

Array.sort mutates in place. If mutation is risky, clone first.

javascript
const sortedCopy = [...rows].sort((a, b) => b.score - a.score);

Choose intentionally:

  • In-place for performance in controlled contexts.
  • Immutable copy for safer shared-state workflows.

Performance Tips

Sorting is usually O(n log n), but comparator overhead often dominates.

Practical optimizations:

  • Precompute expensive derived keys.
  • Avoid allocations inside comparator.
  • Keep comparator logic simple and pure.

For very large datasets, consider server-side indexed sorting or pipeline-level pre-aggregation instead of repeatedly sorting full arrays.

Testing Strategy

Add tests for:

  • Equal-key ties.
  • Null and undefined entries.
  • Locale-sensitive text.
  • Deterministic pagination boundaries.
  • Mutation expectations.

Sorting bugs are often silent, so edge-case tests are high value.

Cross-Service Consistency

If backend and frontend both sort result arrays, define one shared ordering contract in API documentation. Differences in locale collation, null handling, or tie-breakers can produce inconsistent views across clients. Keeping one contract with explicit examples prevents subtle ranking mismatches and reduces debugging effort when users report order discrepancies.

Explicit examples in documentation make these contracts easier for client teams to implement consistently.

Common Pitfalls

  • Using default lexical sort for numeric values.
  • Omitting tie-breakers and causing unstable ordering.
  • Ignoring null policy and getting environment-dependent output.
  • Sorting shared arrays in place and creating hidden side effects.
  • Mixing frontend and backend sorting rules without one documented contract.

Summary

  • Define ordering semantics before writing comparator logic.
  • Use explicit numeric and object comparators for predictable results.
  • Handle ties and nulls deliberately for stable output.
  • Choose in-place or immutable sorting based on state-safety needs.
  • Validate edge cases to keep ranking and pagination behavior reliable.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.