TalentJR

🟨 JavaScript tutorial for beginners · Class 9 · Lesson 2 of 18 · Free

Arrays & Methods – find, some, every, reduce, sort and Chaining in JavaScript

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Search an array with find, findIndex, some and every
  • Add up or combine an array into one value with reduce
  • Sort numbers and objects correctly, and chain filter, map and sort together

The class teacher has everyone's marks in one array. She wants the topper, the class total, whether anyone failed, and a ranked list — before the PTM starts in ten minutes. With the array methods in this lesson, each of those is one short line of JavaScript.

How do I find one item in a JavaScript array?

In Class 8 Lesson 8 you used map, filter and forEach. filter gives back all items that pass a test. Often you want just the first one. That is what `find` does.

`find` returns the first matching item, or `undefined` if nothing matches. `findIndex` returns its position instead, or -1 if nothing matches.

Each of these takes a small test function, like `(s) => s.marks > 90`. JavaScript calls it once for each item until the test says true.

🎬 How JavaScript thinks — step 1 of 12JavaScript is about to run line 1
▶const students = [
2 { name: "Asha", marks: 78 },
3 { name: "Kabir", marks: 95 },
4 { name: "Zoya", marks: 99 }
5];
6const star = students.find((s) => {
7 console.log("checking", s.name);
8 return s.marks > 90;
9});
10console.log(star);
11
12const pos = students.findIndex((s) => s.name === "Zoya");
13console.log(pos);
14
15const missing = students.find((s) => s.marks === 100);
16console.log(missing);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
checking Asha
checking Kabir
{ name: "Kabir", marks: 95 }
2
undefined

💡 Look at the output: find checks Asha, then Kabir, and stops. It never checks Zoya, because it already found a match.

How do some() and every() check a whole array in JavaScript?

Sometimes you only need a yes or no answer. `some` asks: does at least one item pass the test? `every` asks: do all items pass?

Both return `true` or `false`, so they fit nicely inside an `if`.

Like `find`, they stop early. `some` stops at the first true. `every` stops at the first false.

🟨 JavaScript — you can edit this code
Console output
Anyone below 35? true
Everyone passed? false
All marks look valid.
Has a 95? true

💡 Try it: change 32 to 40 and run again. Both answers flip.

How does reduce() add up an array in JavaScript?

`reduce` squeezes a whole array into one value. Think of a running total on a cricket scoreboard.

It takes a function with two inputs: the total so far (often called `acc`, short for accumulator) and the current item. Whatever you return becomes the new total.

The second argument to `reduce` (here 0) is the starting total. Always give it — you will see why in the mistakes.

The second example uses the short arrow form, with no { } and no return. It does exactly the same job in one line.

🎬 How JavaScript thinks — step 1 of 14JavaScript is about to run line 1
▶const overs = [8, 12, 4, 10];
2
3const total = overs.reduce((acc, runs) => {
4 const next = acc + runs;
5 return next;
6}, 0);
7console.log(`Total runs: ${total}`);
8
9const best = overs.reduce((acc, runs) => (runs > acc ? runs : acc), 0);
10console.log(`Best over: ${best}`);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Total runs: 34
Best over: 12

💡 Watch acc in the steps: 0 → 8 → 20 → 24 → 34.

Why does JavaScript sort numbers wrongly, and how do I fix it?

`sort()` with nothing inside sorts items as text, like words in a dictionary. As text, "100" comes before "9", because "1" comes before "9".

To sort numbers, give a compare function `(a, b) => a - b`. If the answer is negative, a goes first. `b - a` sorts from biggest to smallest.

Careful: `sort` changes the original array. To keep the original, sort a copy: `[...marks].sort(...)`.

🟨 JavaScript — you can edit this code
Console output
[100, 25, 3, 9]
[3, 9, 25, 100]
[100, 25, 9, 3]
Original: [9, 100, 25, 3]
["Dev", "Isha", "Asha"]

💡 Words sort fine with plain sort(): ["mango", "apple"].sort() gives ["apple", "mango"].

How do I chain filter, map and sort together in JavaScript?

Most array methods return a new array. So you can call the next method straight away, one after another. This is called chaining.

Read a chain from top to bottom like a recipe: keep only Class 9 students, sort by marks, then turn each student into a line of text.

Put each step on its own line. It is much easier to read and to fix.

🟨 JavaScript — you can edit this code
Console output
["1. Tara (96)", "2. Meera (81)", "3. Kabir (58)"]
Average: 81.8

💡 map gives a second input, the index i. We use i + 1 for the rank.

How do I show a sorted leaderboard on a web page?

Now put it on a page. The array is the single source of truth. A `render` function rebuilds the list from the array each time.

Click the buttons. Each one sorts a copy of the array a different way and calls `render` again.

This idea — change the data, then redraw — is how most real apps work.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Dev, Asha, Isha

💡 a.name.localeCompare(b.name) is the safe way to compare words in a sort.

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

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

Question 2. What does this print?

console.log([3, 5, 8, 6].find((x) => x > 4));

Question 3. What does this print?

console.log([2, 3].reduce((acc, n) => acc + n, 10));

🧩 Your challenge

Write a school canteen bill. The order is an array of objects { item, price, qty }. Use reduce to get the total bill, find to get the first item costing more than ₹40, every to check that each qty is at least 1, and a chain of sort + map to list item names from the costliest line (price × qty) to the cheapest. Expected output: Total: ₹230 First item above ₹40: veg sandwich All quantities OK? true Costliest first: ["samosa", "lassi", "veg sandwich", "chai"]

Expected output in the console:
Total: ₹230
First item above ₹40: veg sandwich
All quantities OK? true
Costliest first: ["samosa", "lassi", "veg sandwich", "chai"]
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const marks = [9, 100, 25];
marks.sort();
console.log("Lowest:", marks[0]);

No error, but it prints "Lowest: 100" — as text, "100" comes before "25" and "9".

✅ Right

const marks = [9, 100, 25];
marks.sort((a, b) => a - b);
console.log("Lowest:", marks[0]);

Plain sort() compares text, not numbers. Give the compare function (a, b) => a - b to sort numbers.

❌ Wrong

const todayRuns = [];
const total = todayRuns.reduce((acc, r) => acc + r);
console.log(total);

TypeError: Reduce of empty array with no initial value

✅ Right

const todayRuns = [];
const total = todayRuns.reduce((acc, r) => acc + r, 0);
console.log(total);

Without a starting value, reduce uses the first item as the start. An empty array has no first item, so it crashes. Always pass a start like 0.

❌ Wrong

const students = [{ name: "Asha", marks: 78 }];
const topper = students.find((s) => s.marks > 90);
console.log(topper.name);

TypeError: Cannot read properties of undefined (reading 'name')

✅ Right

const students = [{ name: "Asha", marks: 78 }];
const topper = students.find((s) => s.marks > 90);
if (topper) {
  console.log(topper.name);
} else {
  console.log("Nobody scored above 90.");
}

find returns undefined when nothing matches, and undefined has no properties. Check the result before using it.

📌 Remember

  • find gives the first matching item (or undefined); findIndex gives its position (or -1).
  • some = is at least one true? every = are all true? Both return true or false.
  • reduce((acc, item) => …, start) turns an array into one value, like a total.
  • sort() compares text; use (a, b) => a - b for numbers, and sort a copy with [...arr] to keep the original.
  • Chain filter → sort → map, one step per line, to go from raw data to a ready list.

Finished the quiz and the challenge?

Questions students ask

What is the difference between find and filter in JavaScript?

filter returns a new array with every item that passes the test, even if that is zero or one item. find returns just the first matching item itself, not inside an array. Use find when you expect one answer, like a student with a given roll number.

Why does JavaScript sort [10, 9, 1] as [1, 10, 9]?

The default sort turns items into text and sorts them like dictionary words. "10" starts with "1", so it comes before "9". Pass (a, b) => a - b to sort numbers by their value.

Is reduce hard to learn?

It feels strange at first because it has two inputs. Think of acc as a running total on a scoreboard, and run the traced example to watch it grow. After a few tries it becomes easy.

Does map or sort change the original array?

map, filter, find, some, every and reduce never change the original array. sort (and push, pop, splice) do change it. Copy first with [...arr] if you still need the original order.