JavaScript Array Sorting and Searching: sort, toSorted, Comparators and Binary Search
Sorting looks simple until [10, 9, 1].sort() returns [1, 10, 9]. JavaScript’s default sort compares items as text, which surprises everyone the first time. Testers sort and search all the time: checking that a table is sorted by price, finding the newest order, picking the slowest test. In this lesson you will learn how sorting really works, how to write comparator functions for numbers, strings, dates and objects, how to sort by several keys, and how to search arrays efficiently.
📖 What You’ll Learn: how the default sort works and why it breaks numbers, comparator functions, ascending and descending order, sorting strings with localeCompare and Intl.Collator, sorting dates, sorting objects by one or more keys, sort stability, sort versus toSorted, checking whether an array is sorted, linear search methods, and binary search on sorted data.
🔤 How the Default sort() Works
Definition: arr.sort() sorts the array in place (it mutates the array) and returns the same array. Without a compare function, it converts every item to a string and sorts by UTF-16 code units, which is alphabetical order for simple text.
📄 default-sort.js
console.log(["webkit", "chromium", "firefox"].sort()); // strings: fine
console.log([10, 9, 1, 100, 25].sort()); // numbers as text: wrong!
console.log(["b", "B", "a", "A"].sort()); // uppercase before lowercase
console.log([true, false, null, undefined, 3].sort()); // undefined always goes last
⌨️ Terminal
node default-sort.js
🖥️ Output
[ 'chromium', 'firefox', 'webkit' ]
[ 1, 10, 100, 25, 9 ]
[ 'A', 'B', 'a', 'b' ]
[ 3, false, null, true, undefined ]
Compared as text, "100" comes before "25" because "1" comes before "2". For anything other than simple strings, always pass a compare function.
⚖️ Comparator Functions
Definition: a comparator is a function (a, b) => number that tells sort the order of two items:
| Comparator returns | Meaning |
|---|---|
| A negative number | a comes before b |
| A positive number | b comes before a |
| 0 | Keep their current order |
📄 numbers.js
const scores = [10, 9, 1, 100, 25];
console.log(scores.toSorted((a, b) => a - b)); // ascending
console.log(scores.toSorted((a, b) => b - a)); // descending
console.log(scores); // toSorted kept the original
⌨️ Terminal
node numbers.js
🖥️ Output
[ 1, 9, 10, 25, 100 ]
[ 100, 25, 10, 9, 1 ]
[ 10, 9, 1, 100, 25 ]
a - b is negative when a is smaller, so smaller numbers come first. Swap to b - a for descending order.
⚠️ Watch out: A comparator must return a number. Returning a boolean such as (a, b) => a > b is a common bug: false becomes 0 and true becomes 1, never negative, so the result depends on the engine and is often wrong.
📄 boolean-bug.js
const values = [3, 1, 2, 5, 4];
console.log(values.toSorted((a, b) => a > b)); // boolean comparator: not reliable
console.log(values.toSorted((a, b) => a - b)); // correct
⌨️ Terminal
node boolean-bug.js
🖥️ Output
[ 3, 1, 2, 5, 4 ]
[ 1, 2, 3, 4, 5 ]
🔠 Sorting Strings Correctly
The default order puts "Zebra" before "apple" and handles accents poorly. Use localeCompare, or an Intl.Collator for speed when sorting many items:
📄 strings.js
const names = ["ravi", "Asha", "émile", "Bala", "zoya", "Ölaf"];
console.log(names.toSorted());
console.log(names.toSorted((a, b) => a.localeCompare(b)));
console.log(names.toSorted((a, b) => b.localeCompare(a))); // Z to A
const collator = new Intl.Collator("en", { sensitivity: "base", numeric: true });
console.log(["file10.txt", "file2.txt", "file1.txt"].toSorted(collator.compare));
⌨️ Terminal
node strings.js
🖥️ Output
[ 'Asha', 'Bala', 'ravi', 'zoya', 'Ölaf', 'émile' ]
[ 'Asha', 'Bala', 'émile', 'Ölaf', 'ravi', 'zoya' ]
[ 'zoya', 'ravi', 'Ölaf', 'émile', 'Bala', 'Asha' ]
[ 'file1.txt', 'file2.txt', 'file10.txt' ]
numeric: true gives “natural” order, so file2 comes before file10, the way file explorers show them.
📅 Sorting Dates
Subtracting two Date objects gives the difference in milliseconds, which works as a comparator. ISO date strings (YYYY-MM-DD) also sort correctly as text.
📄 dates.js
const orders = [
{ id: 1, placed: "2026-11-20T09:15:00Z" },
{ id: 2, placed: "2026-11-23T14:02:00Z" },
{ id: 3, placed: "2026-10-31T18:40:00Z" },
];
const newestFirst = orders.toSorted((a, b) => new Date(b.placed) - new Date(a.placed));
console.log(newestFirst.map((o) => o.id));
const oldestFirst = orders.toSorted((a, b) => a.placed.localeCompare(b.placed)); // ISO strings
console.log(oldestFirst.map((o) => o.id));
⌨️ Terminal
node dates.js
🖥️ Output
[ 2, 1, 3 ]
[ 3, 1, 2 ]
⚠️ Watch out: Text dates in other formats, such as "23/11/2026", do not sort correctly as strings. Parse them into Date objects or ISO strings first.
🗂️ Sorting Objects by One or More Keys
📄 objects.js
const tests = [
{ name: "login", suite: "auth", ms: 820 },
{ name: "pay card", suite: "pay", ms: 2210 },
{ name: "logout", suite: "auth", ms: 310 },
{ name: "pay upi", suite: "pay", ms: 2210 },
{ name: "add item", suite: "cart", ms: 1430 },
];
// One key
const slowestFirst = tests.toSorted((a, b) => b.ms - a.ms);
console.log(slowestFirst.map((t) => `${t.name}:${t.ms}`));
// Two keys: suite A-Z, then duration ascending within each suite
const bySuiteThenTime = tests.toSorted((a, b) => a.suite.localeCompare(b.suite) || a.ms - b.ms);
console.log(bySuiteThenTime.map((t) => `${t.suite}/${t.name}:${t.ms}`));
⌨️ Terminal
node objects.js
🖥️ Output
[
'pay card:2210',
'pay upi:2210',
'add item:1430',
'login:820',
'logout:310'
]
[
'auth/logout:310',
'auth/login:820',
'cart/add item:1430',
'pay/pay card:2210',
'pay/pay upi:2210'
]
a.suite.localeCompare(b.suite) || a.ms - b.ms works because when the suites are equal, localeCompare returns 0 (falsy), so || moves on to the second comparison.
A small helper makes multi-key sorting readable and reusable:
📄 by-helper.js
const by = (...keys) => (a, b) => {
for (const key of keys) {
const desc = key.startsWith("-");
const k = desc ? key.slice(1) : key;
const cmp = typeof a[k] === "number" ? a[k] - b[k] : String(a[k]).localeCompare(String(b[k]));
if (cmp !== 0) return desc ? -cmp : cmp;
}
return 0;
};
const products = [
{ name: "Pen", category: "office", price: 10 },
{ name: "Lamp", category: "home", price: 899 },
{ name: "Stapler", category: "office", price: 150 },
{ name: "Mug", category: "home", price: 199 },
];
console.log(products.toSorted(by("category", "-price")).map((p) => `${p.category}:${p.name}:${p.price}`));
⌨️ Terminal
node by-helper.js
🖥️ Output
[
'home:Lamp:899',
'home:Mug:199',
'office:Stapler:150',
'office:Pen:10'
]
🧷 Stability and sort vs toSorted
Definition: a sort is stable if items that compare as equal keep their original order. Since ES2019, Array.prototype.sort is guaranteed to be stable, so sorting by a second key after a first sort keeps the first order among ties.
📄 stable.js
const results = [
{ test: "a", status: "failed" },
{ test: "b", status: "passed" },
{ test: "c", status: "failed" },
{ test: "d", status: "passed" },
];
const failedFirst = results.toSorted((x, y) => (x.status === "failed" ? 0 : 1) - (y.status === "failed" ? 0 : 1));
console.log(failedFirst.map((r) => r.test)); // a before c, b before d: original order kept
⌨️ Terminal
node stable.js
🖥️ Output
[ 'a', 'c', 'b', 'd' ]
sort(fn) | toSorted(fn) (ES2023) | |
|---|---|---|
| Changes the original array | Yes | No |
| Returns | The same array | A new sorted array |
| Use when | You own the array and want to change it | Shared data, test fixtures, function inputs |
✅ Checking Whether an Array Is Sorted
A UI test often checks that a column is sorted after clicking its header. Compare each item with the next one, or compare with a sorted copy:
📄 is-sorted.js
const isSorted = (arr, compare) => arr.every((item, i) => i === 0 || compare(arr[i - 1], item) <= 0);
const pricesAsc = [10, 45, 45, 199, 899];
const pricesBroken = [10, 199, 45, 899];
console.log(isSorted(pricesAsc, (a, b) => a - b), isSorted(pricesBroken, (a, b) => a - b));
const namesOnPage = ["Asha", "bala", "Ravi", "zoya"];
const expected = namesOnPage.toSorted((a, b) => a.localeCompare(b));
console.log(JSON.stringify(namesOnPage) === JSON.stringify(expected));
⌨️ Terminal
node is-sorted.js
🖥️ Output
true false
true
💡 Tip: Use the same comparison rules as the application (case-insensitive? natural numbers? locale?). A test that sorts with the default sort() will report false failures for correctly sorted, case-insensitive columns.
🔍 Searching Arrays
| Need | Method | Returns |
|---|---|---|
| Is a value present? | includes(value) | Boolean |
| Where is a value? | indexOf(value) / lastIndexOf | Index or -1 |
| First item matching a rule | find(fn) / findLast(fn) | Item or undefined |
| Index of first item matching a rule | findIndex(fn) / findLastIndex(fn) | Index or -1 |
| Does any / every item match? | some(fn) / every(fn) | Boolean |
| All items matching a rule | filter(fn) | Array |
These are linear searches: they check items one by one, which is fine for typical data. For large sorted arrays, binary search is much faster: it halves the search range at every step.
📄 binary-search.js
function binarySearch(sorted, target) {
let low = 0;
let high = sorted.length - 1;
let steps = 0;
while (low <= high) {
steps++;
const mid = Math.floor((low + high) / 2);
if (sorted[mid] === target) return { index: mid, steps };
if (sorted[mid] < target) low = mid + 1;
else high = mid - 1;
}
return { index: -1, steps };
}
const ids = Array.from({ length: 1_000_000 }, (_, i) => i * 2); // sorted even numbers
console.log(binarySearch(ids, 777_778));
console.log(binarySearch(ids, 777_777)); // odd: not present
console.log("indexOf finds it too:", ids.indexOf(777_778));
⌨️ Terminal
node binary-search.js
🖥️ Output
{ index: 388889, steps: 20 }
{ index: -1, steps: 20 }
indexOf finds it too: 388889
Binary search needed about 20 steps for a million items, where a linear search might check up to a million. It only works when the array is sorted by the same rule you search with.
🧪 Tester Scenario: Verify Sorting After Clicking a Column
The values below simulate the price column of a product table read from a page before and after clicking “Sort by price ↓”. The check parses the text, then verifies the order and that no rows were lost:
📄 verify-sort.js
const before = ["₹1,299.00", "₹45.50", "₹899.00", "₹10.00", "₹45.50"];
const after = ["₹1,299.00", "₹899.00", "₹45.50", "₹45.50", "₹10.00"];
const toNumber = (text) => Number(text.replace(/[^\d.]/g, ""));
const afterNums = after.map(toNumber);
const descending = afterNums.every((p, i) => i === 0 || afterNums[i - 1] >= p);
const sameItems = JSON.stringify(before.map(toNumber).toSorted((a, b) => b - a)) === JSON.stringify(afterNums);
console.log("sorted descending:", descending);
console.log("same rows, nothing lost:", sameItems);
console.log("highest:", afterNums[0], "lowest:", afterNums.at(-1));
⌨️ Terminal
node verify-sort.js
🖥️ Output
sorted descending: true
same rows, nothing lost: true
highest: 1299 lowest: 10
Checking that the multiset of values is unchanged catches a real class of bugs: sorting implementations that drop, duplicate or re-fetch rows.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Sort [40, 100, 1, 5, 25, 10] in ascending and descending order without changing the original array.
Show answer
📄 practice1.js
const nums = [40, 100, 1, 5, 25, 10];
console.log(nums.toSorted((a, b) => a - b), nums.toSorted((a, b) => b - a), nums);🖥️ Output
[ 1, 5, 10, 25, 40, 100 ] [ 100, 40, 25, 10, 5, 1 ] [ 40, 100, 1, 5, 25, 10 ]Q2. Sort ["banana", "Apple", "cherry", "apple"] alphabetically, ignoring case.
Show answer
📄 practice2.js
const fruits = ["banana", "Apple", "cherry", "apple"];
console.log(fruits.toSorted((a, b) => a.localeCompare(b, "en", { sensitivity: "base" })));🖥️ Output
[ 'Apple', 'apple', 'banana', 'cherry' ]Q3. Sort users by age (youngest first) and, for equal ages, by name.
const users = [
{ name: "Ravi", age: 30 },
{ name: "Asha", age: 25 },
{ name: "Bala", age: 30 },
];Show answer
📄 practice3.js
const users = [
{ name: "Ravi", age: 30 },
{ name: "Asha", age: 25 },
{ name: "Bala", age: 30 },
];
console.log(users.toSorted((a, b) => a.age - b.age || a.name.localeCompare(b.name)).map((u) => u.name));🖥️ Output
[ 'Asha', 'Bala', 'Ravi' ]Q4. Find the 3 slowest tests from [{ t: "a", ms: 400 }, { t: "b", ms: 2200 }, { t: "c", ms: 900 }, { t: "d", ms: 3100 }, { t: "e", ms: 150 }].
Show answer
📄 practice4.js
const tests = [{ t: "a", ms: 400 }, { t: "b", ms: 2200 }, { t: "c", ms: 900 }, { t: "d", ms: 3100 }, { t: "e", ms: 150 }];
console.log(tests.toSorted((x, y) => y.ms - x.ms).slice(0, 3).map((x) => x.t));🖥️ Output
[ 'd', 'b', 'c' ]Q5. Write isSortedDesc(arr) that returns true if numbers never increase. Test [9, 7, 7, 2] and [9, 3, 5].
Show answer
📄 practice5.js
const isSortedDesc = (arr) => arr.every((v, i) => i === 0 || arr[i - 1] >= v);
console.log(isSortedDesc([9, 7, 7, 2]), isSortedDesc([9, 3, 5]));🖥️ Output
true falseQ6. Sort the date strings ["23/11/2026", "05/01/2026", "30/06/2025"] from oldest to newest.
Show answer
📄 practice6.js
const dates = ["23/11/2026", "05/01/2026", "30/06/2025"];
const toIso = (d) => d.split("/").reverse().join("-");
console.log(dates.toSorted((a, b) => toIso(a).localeCompare(toIso(b))));🖥️ Output
[ '30/06/2025', '05/01/2026', '23/11/2026' ]Converting DD/MM/YYYY to YYYY-MM-DD makes simple string comparison correct.
🧠 MCQ Quiz: Sorting and Searching Arrays
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What does
[10, 9, 1].sort()return?Answer: [1, 10, 9]. The default sort compares items as strings. - Which comparator sorts numbers in ascending order?Answer: (a, b) => a – b. A negative result puts a before b.
- What does a comparator returning 0 mean?Answer: Keep the two items in their current order. With a stable sort, equal items keep their order.
- Does
sortchange the original array?Answer: Yes, it sorts in place. Use toSorted for a new array. - Why is
(a, b) => a > ba bad comparator?Answer: It returns booleans, never a negative number. Comparators must return negative, zero or positive numbers. - How do you sort strings so that “apple” and “Zebra” are in natural alphabetical order?Answer: (a, b) => a.localeCompare(b). localeCompare follows language rules rather than code units.
- How do you sort by name, then by age for equal names?Answer: (a, b) => a.name.localeCompare(b.name) || a.age – b.age. The second comparison is used only when the first returns 0.
- Since which edition is Array.prototype.sort guaranteed to be stable?Answer: ES2019. Equal elements keep their original relative order.
- When can you use binary search?Answer: When the array is sorted by the same rule you search with. It relies on the order to discard half the range at each step.
- Where does sort() put undefined values?Answer: At the end. undefined values are always moved to the end, without calling the comparator.
💼 Interview Questions and Answers
Q1. Why does [1, 10, 2].sort() not sort numerically, and how do you fix it?
Without a compare function, sort converts elements to strings and compares UTF-16 code units, so “10” comes before “2”. Pass a numeric comparator: arr.sort((a, b) => a - b) for ascending or (a, b) => b - a for descending, or use toSorted to avoid mutating the array.
Q2. How do you sort an array of objects by multiple fields?
Write a comparator that compares the first field and falls back to the next only when the first is equal: (a, b) => a.lastName.localeCompare(b.lastName) || a.firstName.localeCompare(b.firstName) || a.age - b.age. Because sort is stable (ES2019+), you can also sort by the least important key first and the most important key last.
Q3. How would you test that a table column is sorted correctly?
- Read the column values (for example
allTextContents()) and normalise them: trim, parse numbers and dates. - Build the expected order with the same rules as the application (direction, case sensitivity, locale, natural number order).
- Assert the actual array equals the expected sorted copy, or that every adjacent pair is in order.
- Also assert the count and the set of values are unchanged, so missing or duplicated rows are caught.
- Test ties, empty values and pagination (sorted across pages, not just within one page).
Q4. What is the time complexity of sorting and of binary search?
Engine sorts are O(n log n) on average (V8 uses TimSort). Linear search methods (indexOf, find, includes) are O(n). Binary search on a sorted array is O(log n): a million items need about 20 comparisons. Sorting once and then running many binary searches pays off only when you search many times.
❓ Frequently Asked Questions
🤔 How do I sort an array in descending order?
For numbers use arr.toSorted((a, b) => b - a); for strings use (a, b) => b.localeCompare(a). Or sort ascending and call toReversed().
🤔 How do I sort without changing the original array?
Use toSorted(compareFn) (ES2023), or copy first: [...arr].sort(compareFn).
🤔 How do I shuffle an array randomly?
Do not use sort(() => Math.random() - 0.5); it is biased. Use the Fisher–Yates algorithm: loop from the end and swap each item with a random earlier one.
🤔 Is localeCompare slow for big arrays?
It can be when called thousands of times. Create one Intl.Collator and pass collator.compare as the comparator.
🏁 Summary
- The default
sort()compares items as strings, so always pass a comparator for numbers, dates and objects. - A comparator returns negative (a first), positive (b first) or 0 (keep order); use
a - bfor numbers andlocaleComparefor text. - Chain comparisons with
||to sort by several keys; sort is stable since ES2019. sortmutates;toSortedreturns a new array, which is safer for shared data.- Use linear search methods for everyday searches and binary search for large sorted arrays.
Next, continue with Lesson 33: Objects. This completes Module 6. Module 7 continues with objects and collections.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in