JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 6: Arrays and CollectionsLesson 28 of 150About 45 minutes

Lesson 28: Searching and sorting arrays

01Opening question

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.

You need: Lesson 27: Adding and removing elements, Lesson 24: Arrow functions

Skills practised: Arrays, Searching arrays, Sorting arrays.

04Explanation

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.

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.

Open the full glossary

06Visual learning object

Array sorting laboratory. Sort the same array with the default sort and with compare functions and see why numbers need a - b.

Loading the interactive object…

Open the full Array sorting laboratory page with its guided experiment.

07Examples

ex-028-01Searching by value Browser-executable JavaScript

includes answers yes/no; indexOf gives a position.

const tags = ["sale", "new", "eco", "new"];
console.log(tags.includes("eco"));
console.log(tags.indexOf("new"));
console.log(tags.lastIndexOf("new"));
console.log(tags.indexOf("vip"));
Sample input
None
Expected output
true 1 3 -1
Common mistake
Treating indexOf's -1 as true in an if.
Try this
Check whether "Sale" (capital S) is included.
Source
examples/ex-028-01-search-by-value.js (repository pending publication)

ex-028-02Searching by a rule Browser-executable JavaScript

find returns the element; findIndex returns its position.

const prices = [12, 48, 75, 30];
const firstBig = prices.find((p) => p > 40);
const where = prices.findIndex((p) => p > 40);
const none = prices.find((p) => p > 100);
console.log(firstBig, where, none);
Sample input
None
Expected output
48 1 undefined
Common mistake
Expecting find to return every match; it returns the first only.
Try this
Find the first price below 20.
Source
examples/ex-028-02-find-by-rule.js (repository pending publication)

ex-028-03Sorting numbers correctly Browser-executable JavaScript

Default sort compares text; a - b compares numbers.

const scores = [40, 100, 9, 25];
console.log([...scores].sort());
console.log([...scores].sort((a, b) => a - b));
console.log([...scores].sort((a, b) => b - a));
console.log(scores);
Sample input
None
Expected output
[100, 25, 40, 9] [9, 25, 40, 100] [100, 40, 25, 9] [40, 100, 9, 25]
Common mistake
Calling sort() on numbers without a compare function.
Try this
Sort the scores and print only the top two.
Source
examples/ex-028-03-number-sort.js (repository pending publication)

ex-028-04Sorting objects by a property Browser-executable JavaScript

The compare function reads the property to compare.

const products = [
  { name: "Lamp", price: 30 },
  { name: "Rug", price: 12 },
  { name: "Desk", price: 90 }
];
const cheapest = [...products].sort((a, b) => a.price - b.price);
console.log(cheapest.map((p) => p.name).join(" < "));
const byName = [...products].sort((a, b) => a.name.localeCompare(b.name));
console.log(byName[0].name);
Sample input
None
Expected output
Rug < Lamp < Desk Desk
Common mistake
Subtracting strings in a compare function, which gives NaN.
Try this
Sort by price from most to least expensive.
Source
examples/ex-028-04-sort-objects.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the number sort

Add a compare function for numbers.

const times = [120, 15, 9, 45];
times.sort();
console.log("Fastest first:", times.join(", "));

Find the order

Use find with an object property.

const orders = [
  { id: "A1", total: 20 },
  { id: "B7", total: 55 },
  { id: "C3", total: 12 }
];
// TODO: find the order with id "B7" and print its total

Top three without changing the data

Sort a copy by a property and take the first elements.

const players = [
  { name: "Ada", score: 82 },
  { name: "Grace", score: 95 },
  { name: "Linus", score: 70 },
  { name: "Margaret", score: 88 }
];

09Prediction

Commit to an answer first, then run the real code to compare.

const a = [3, 20, 100];
console.log(a.sort().join(" "));
console.log(a.indexOf(3));

What two lines are printed?

10Debugging investigation

"Cheapest first" shows the most expensive item

Prices of 8, 75 and 120 are sorted "cheapest first", but the first card shows $120.

const prices = [75, 8, 120];
const sorted = [...prices].sort();
console.log(`Cheapest: $${sorted[0]}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Sorting a product grid

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.

const items = [{ n: "Mug", p: 8 }, { n: "Bag", p: 30 }];
const byPrice = [...items].sort((a, b) => b.p - a.p);
console.log(byPrice[0].n, items[0].n);

12Knowledge check

1. What is printed?

console.log(["a", "b"].indexOf("x"));
  • -1
  • 0
  • false
  • undefined

2. What is printed?

console.log([10, 1, 2].sort());
  • [1, 2, 10]
  • [1, 10, 2]
  • [10, 2, 1]
  • [2, 1, 10]

3. What does find return when nothing matches?

  • -1
  • null
  • undefined
  • false

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.

16AI learning prompts

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 explanation searching 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 prediction searching 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.
Debugging searching 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 generation searching 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 review searching 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.