A product list shows prices 5, 25 and 100. After sorting, it shows 100, 25, 5 in ascending order. How can sorting numbers go wrong?
Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.
02Start with working code
Default sort compares values as text. A compare function sorts numbers correctly.
const prices = [25, 5, 100];
console.log([...prices].sort());
console.log([...prices].sort((a, b) => a - b));
console.log(prices.includes(5), prices.indexOf(100));
03Objective and prerequisites
Learning objective: Search arrays with includes, indexOf, find and findIndex, sort strings and numbers correctly with compare functions, and avoid sorting shared data in place.
includes(x) answers yes or no. indexOf(x) gives the position of the first match, or -1 when there is none.
find(fn) returns the first element for which the function returns true, or undefined. findIndex(fn) returns its index, or -1. Use them when you search by a rule, such as "first price above 50".
sort() without arguments converts elements to strings and sorts them alphabetically, so [25, 5, 100] becomes [100, 25, 5].
To sort numbers, pass a compare function: (a, b) => a - b for ascending, (a, b) => b - a for descending. sort changes the array, so copy it first with [...list] when the original order matters.
The compare function returns a negative number (a first), positive (b first) or 0 (keep order). Since ES2019 sort is stable, so equal elements keep their relative order, which lets you sort by several keys in sequence.
For human-readable text use a.localeCompare(b) or an Intl.Collator, which handle accents and case properly; for objects, sort by a property: (a, b) => a.price - b.price.
toSorted() (ES2023) returns a sorted copy. includes uses SameValueZero, so it finds NaN; indexOf uses strict equality and does not.
Linear searches are O(n). For repeated lookups by key build a Map once; for sorted data binary search is O(log n).
05Definitions
includes
Returns true when an array contains a value.
indexOf
Returns the index of the first matching value, or -1.
find / findIndex
Return the first element (or its index) that passes a test function.
Compare function
A function given to sort that decides which of two elements comes first.
Stable sort
A sort that keeps equal elements in their original order.
A shop lets customers sort by price or name. Each sort works on a copy so the original order (the shop's featured order) can be restored when the filter is cleared.
4. Why does this always run the if body, even when "Ada" is first?
if (!names.indexOf("Ada")) {
console.log("Ada not found");
}
indexOf returns 0 which is falsy
includes would fail too
Strings cannot be searched
The array is empty
5. Which compare function sorts prices from highest to lowest?
(a, b) => a - b
(a, b) => b - a
(a, b) => a > b
() => 0
6. A page needs a sorted view but the original list is used elsewhere. Which is better?
list.sort(cmp)
[...list].sort(cmp)
Both are the same
list.reverse()
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Fix the number sort: Sorted numerically; times is sorted
Find the order: Prints the total; Uses find
Top three without changing the data: Prints the top three; players keeps its order; Works for two players
ex-028-01: output matches the documented expected output
ex-028-02: output matches the documented expected output
ex-028-03: output matches the documented expected output
ex-028-04: output matches the documented expected output
The lesson lives in the companion repository at curriculum/level-02-core-development/module-06-arrays-and-collections/lesson-028-searching-and-sorting-arrays/. Every example on this page is generated from those files.
The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.
15Summary and next steps
includes and indexOf search by value; find and findIndex search by rule.
indexOf and findIndex return -1 when nothing is found.
sort() compares text; pass (a, b) => a - b for numbers.
sort mutates: copy first when the order matters elsewhere.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationsearching and sorting arrays
Context: I am learning searching and sorting arrays in JavaScript.
Task: Explain includes, indexOf, find, findIndex and sort with compare functions, using a product list.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictionsearching and sorting arrays drill
Context: I have practised searching and sorting arrays.
Task: Ask me eight questions about search results and sort orders, including the default text sort of numbers.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debuggingsearching and sorting arrays bug
Context: My numbers sort in a strange order like 100, 25, 5.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationsearching and sorting arrays practice
Context: I finished the searching and sorting arrays exercises.
Task: Create three exercises that search and sort arrays of objects.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewsearching and sorting arrays review
Context: Here is my code that uses searching and sorting arrays.
Task: Review my sorting code for mutation of shared data and incorrect compare functions.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.