Technical skill practice

Sort an Array in JavaScript: Numeric Order and Tie Breakers

JavaScript array sort needs an appropriate comparator for numeric order. Without one, numeric values can appear in string order. sort changes the array it is called on, so choose the receiver deliberately.

The task

Order inspection jobs by ascending duration, then by numeric job ID when durations tie. Keep a separate short number list to expose what default sorting does.

Runnable Node 22 example

const assert = require('node:assert/strict');

const lexical = [12, 3, 20];
lexical.sort();
assert.deepEqual(lexical, [12, 20, 3]);
const jobs = [{id: 8, minutes: 15}, {id: 2, minutes: 5}, {id: 4, minutes: 15}];
const returned = jobs.sort((a, b) => a.minutes - b.minutes || a.id - b.id);
assert.equal(returned, jobs);
assert.deepEqual(jobs.map(job => job.id), [2, 4, 8]);
console.log(JSON.stringify(jobs.map(job => job.id)));

Expected output and explanation

The default example places 20 before 3 because it is not applying numeric magnitude. The record comparator first compares minutes; a zero difference falls through to the ID comparison. That makes the required tie policy explicit rather than dependent on input order.

The identity assertion shows that sort returns the same array it rearranges. The record values are not rewritten, but their positions change. Call toSorted when you specifically need a new sorted container in a supporting runtime, or choose another deliberate nonmutating approach.

Output from the example

[2,4,8]

Pitfall to check

A comparator should return a negative, zero or positive number consistently. Returning only true or false fails to describe both directions. Define a policy for missing or invalid durations before sorting; this fixture contains finite numbers only.

Questions, answered

Does descending numeric order use the same comparator?

Reverse the numeric difference for the intended key, such as b.minutes − a.minutes. Decide separately whether the tie-breaker direction should also change.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.