In the previous tutorial, you learned how to clean and search text. Now it’s time to level up your array skills. You already know push, pop, slice and splice from the Arrays tutorial. In this lesson, we will learn more powerful JavaScript Array Methods that help you search, check, sort and reshape your data with very little code.
Quick Revision: Methods You Already Know
let fruits = ["Apple", "Banana", "Mango"];
fruits.push("Orange"); // add at end
fruits.pop(); // remove from end
fruits.unshift("Grapes"); // add at start
fruits.shift(); // remove from start
console.log(fruits.slice(0, 2)); // copy a part
fruits.splice(1, 1); // remove from original
console.log(fruits.includes("Mango")); // true
Now let’s learn new JavaScript Array Methods. For many of them, we will use a function inside the method. This is called a callback function. Don’t worry, we will keep it simple.
What is a Callback Function?
A callback is a function that you give to another function. The array method calls your function for every item, one by one.
let numbers = [10, 20, 30];
numbers.forEach(function (num) {
console.log(num * 2);
});
// Same thing with an arrow function (shorter)
numbers.forEach((num) => console.log(num * 2));
// Output: 20 40 60
Here num is the current item. The method runs your function for each item automatically.
1. find()
Returns the first item that matches your condition. If nothing matches, it returns undefined.
let numbers = [5, 12, 8, 130, 44];
let result = numbers.find((num) => num > 10);
console.log(result); // 12 (first number above 10)
let none = numbers.find((num) => num > 500);
console.log(none); // undefined
It becomes really useful with an array of objects:
let students = [
{ id: 1, name: "Ali", marks: 78 },
{ id: 2, name: "Sara", marks: 92 },
{ id: 3, name: "Bilal", marks: 45 }
];
let student = students.find((s) => s.id === 2);
console.log(student); // { id: 2, name: "Sara", marks: 92 }
console.log(student.name); // Sara
let topper = students.find((s) => s.marks > 90);
console.log(topper.name); // Sara
2. findIndex()
Works like find(), but returns the position (index). If nothing matches, it returns -1.
let numbers = [5, 12, 8, 130, 44];
console.log(numbers.findIndex((num) => num > 10)); // 1
console.log(numbers.findIndex((num) => num > 500)); // -1
// Real use: remove a student by id
let students = [
{ id: 1, name: "Ali" },
{ id: 2, name: "Sara" },
{ id: 3, name: "Bilal" }
];
let index = students.findIndex((s) => s.id === 2);
if (index !== -1) {
students.splice(index, 1);
}
console.log(students); // Ali and Bilal remain
3. findLast() and findLastIndex()
Same idea, but they search from the end of the array.
let numbers = [5, 12, 8, 130, 44];
console.log(numbers.findLast((num) => num < 50)); // 44
console.log(numbers.findLastIndex((num) => num < 50)); // 4
4. some()
Checks if at least one item matches. Returns true or false.
let ages = [15, 17, 22, 14];
console.log(ages.some((age) => age >= 18)); // true (22 is adult)
console.log(ages.some((age) => age > 50)); // false
// Real use: is there any failed student?
let marks = [78, 92, 35, 66];
let hasFailed = marks.some((m) => m < 40);
console.log(hasFailed); // true
5. every()
Checks if all items match. Returns true or false.
let ages = [20, 25, 30];
console.log(ages.every((age) => age >= 18)); // true (all adults)
let mixedAges = [20, 15, 30];
console.log(mixedAges.every((age) => age >= 18)); // false
// Real use: did everyone pass?
let marks = [78, 92, 55, 66];
let allPassed = marks.every((m) => m >= 40);
console.log(allPassed); // true
Easy trick: some means “any one”, and every means “all”.
| Method | Question it answers | Returns |
|---|---|---|
| find() | Which is the first matching item? | The item or undefined |
| findIndex() | Where is the first matching item? | Index or -1 |
| some() | Does at least one item match? | true or false |
| every() | Do all items match? | true or false |
6. sort() in Depth
You saw basic sorting in the Arrays tutorial. Remember: sort() changes the original array and treats items as text by default.
// Strings: A to Z
let names = ["Sara", "Ali", "Bilal", "Ayesha"];
names.sort();
console.log(names); // ["Ali", "Ayesha", "Bilal", "Sara"]
// Numbers: always use a compare function
let numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 25, 40, 100] (small to big)
numbers.sort((a, b) => b - a);
console.log(numbers); // [100, 40, 25, 5, 1] (big to small)
How does the compare function work?
JavaScript compares two items (a and b) at a time:
- If your function returns a negative number,
agoes beforeb - If it returns a positive number,
bgoes beforea - If it returns 0, the order stays the same
Sorting an array of objects
let students = [
{ name: "Ali", marks: 78 },
{ name: "Sara", marks: 92 },
{ name: "Bilal", marks: 45 }
];
// By marks, high to low
students.sort((a, b) => b.marks - a.marks);
console.log(students.map ? students[0].name : ""); // Sara (topper)
for (let s of students) {
console.log(s.name + ": " + s.marks);
}
// Sara: 92
// Ali: 78
// Bilal: 45
// By name, A to Z
students.sort((a, b) => a.name.localeCompare(b.name));
for (let s of students) {
console.log(s.name);
}
// Ali, Bilal, Sara
Sort without changing the original: toSorted()
let numbers = [40, 100, 1, 5];
let sorted = numbers.toSorted((a, b) => a - b);
console.log(sorted); // [1, 5, 40, 100]
console.log(numbers); // [40, 100, 1, 5] (original is safe)
Similarly, toReversed() gives a reversed copy without touching the original.
7. flat()
Turns an array of arrays into a single array.
let nested = [1, 2, [3, 4], [5, 6]];
console.log(nested.flat()); // [1, 2, 3, 4, 5, 6]
// Deeper nesting: give the depth
let deep = [1, [2, [3, [4]]]];
console.log(deep.flat()); // [1, 2, [3, [4]]]
console.log(deep.flat(2)); // [1, 2, 3, [4]]
console.log(deep.flat(Infinity)); // [1, 2, 3, 4]
8. fill()
Fills an array with one value. Great for creating default data.
let zeros = new Array(5).fill(0);
console.log(zeros); // [0, 0, 0, 0, 0]
let stars = new Array(3).fill("*");
console.log(stars); // ["*", "*", "*"]
let numbers = [1, 2, 3, 4, 5];
numbers.fill(99, 1, 3); // fill(value, start, end)
console.log(numbers); // [1, 99, 99, 4, 5]
9. Array.from()
Creates an array from something else, like a string, or from a range of numbers.
// From a string
console.log(Array.from("Hello")); // ["H", "e", "l", "l", "o"]
// Create numbers 1 to 5
let range = Array.from({ length: 5 }, (value, index) => index + 1);
console.log(range); // [1, 2, 3, 4, 5]
// Create the first 5 even numbers
let evens = Array.from({ length: 5 }, (value, index) => (index + 1) * 2);
console.log(evens); // [2, 4, 6, 8, 10]
10. Array.of() and Array.isArray()
console.log(Array.of(7)); // [7]
console.log(Array.isArray([1, 2])); // true
console.log(Array.isArray("Hi")); // false
11. concat() and the Spread Operator
let a = [1, 2];
let b = [3, 4];
console.log(a.concat(b)); // [1, 2, 3, 4]
console.log([...a, ...b]); // [1, 2, 3, 4] (modern way)
console.log([0, ...a, 99]); // [0, 1, 2, 99]
12. at(), lastIndexOf() and join()
let fruits = ["Apple", "Banana", "Mango", "Banana"];
console.log(fruits.at(0)); // Apple
console.log(fruits.at(-1)); // Banana (last item)
console.log(fruits.lastIndexOf("Banana")); // 3
console.log(fruits.join(" | ")); // Apple | Banana | Mango | Banana
Bonus: map(), filter() and reduce() (Preview)
These three are the most famous JavaScript Array Methods. We will study them in full detail in the Advanced series. Here is a small taste so you are not surprised when you see them:
let numbers = [1, 2, 3, 4, 5];
// map: change every item
console.log(numbers.map((n) => n * 2)); // [2, 4, 6, 8, 10]
// filter: keep only matching items
console.log(numbers.filter((n) => n % 2 === 0)); // [2, 4]
// reduce: combine all items into one value
console.log(numbers.reduce((sum, n) => sum + n, 0)); // 15
Practical Example 1: Product Search
let products = [
{ id: 1, name: "Laptop", price: 85000, inStock: true },
{ id: 2, name: "Mouse", price: 1200, inStock: true },
{ id: 3, name: "Keyboard", price: 3500, inStock: false },
{ id: 4, name: "Monitor", price: 32000, inStock: true }
];
// Find a product by id
let product = products.find((p) => p.id === 3);
console.log(product.name + " - Rs. " + product.price); // Keyboard - Rs. 3500
// Is any product out of stock?
console.log(products.some((p) => !p.inStock)); // true
// Are all products under 100000?
console.log(products.every((p) => p.price < 100000)); // true
// Sort by price, low to high (copy, original safe)
let cheapFirst = products.toSorted((a, b) => a.price - b.price);
for (let p of cheapFirst) {
console.log(p.name + ": " + p.price);
}
// Mouse: 1200
// Keyboard: 3500
// Monitor: 32000
// Laptop: 85000
Practical Example 2: Leaderboard
let players = [
{ name: "Ali", score: 450 },
{ name: "Sara", score: 780 },
{ name: "Bilal", score: 620 },
{ name: "Hina", score: 780 }
];
let leaderboard = players.toSorted((a, b) => b.score - a.score);
for (let i = 0; i < leaderboard.length; i++) {
console.log((i + 1) + ". " + leaderboard[i].name + " - " + leaderboard[i].score);
}
// 1. Sara - 780
// 2. Hina - 780
// 3. Bilal - 620
// 4. Ali - 450
Practical Example 3: Login Check
let users = [
{ email: "ali@example.com", password: "1234" },
{ email: "sara@example.com", password: "abcd" }
];
function login(email, password) {
let user = users.find((u) => u.email === email && u.password === password);
if (user) {
return "Welcome, " + user.email;
}
return "Invalid email or password";
}
console.log(login("ali@example.com", "1234")); // Welcome, ali@example.com
console.log(login("ali@example.com", "wrong")); // Invalid email or password
Practical Example 4: Flatten and Clean Data
let classA = ["Ali", "Sara"];
let classB = ["Bilal", "Hina"];
let classC = ["Usman"];
let allStudents = [classA, classB, classC].flat();
console.log(allStudents); // ["Ali", "Sara", "Bilal", "Hina", "Usman"]
allStudents.sort();
console.log(allStudents.join(", ")); // Ali, Bilal, Hina, Sara, Usman
Practical Example 5: Generate a Table on a Webpage
<table border="1" id="productTable">
<tr><th>Name</th><th>Price</th></tr>
</table>
<script>
let products = [
{ name: "Laptop", price: 85000 },
{ name: "Mouse", price: 1200 },
{ name: "Monitor", price: 32000 }
];
products.sort((a, b) => a.price - b.price);
let rows = "";
for (let p of products) {
rows += "<tr><td>" + p.name + "</td><td>" + p.price + "</td></tr>";
}
document.getElementById("productTable").innerHTML += rows;
</script>
We will learn document.getElementById properly in the DOM tutorials.
Which Method Should I Use?
| I want to… | Use |
|---|---|
| Add or remove at the end | push() / pop() |
| Add or remove at the start | unshift() / shift() |
| Get one item by condition | find() |
| Get the position by condition | findIndex() |
| Check if any item matches | some() |
| Check if all items match | every() |
| Check if a value exists | includes() |
| Sort items | sort() or toSorted() |
| Merge nested arrays | flat() |
| Create a default array | fill() or Array.from() |
Common Mistakes to Avoid
let numbers = [5, 12, 8];
// Mistake 1: forgetting that find() returns the item, not true/false
let found = numbers.find((n) => n > 10);
console.log(found); // 12 (not true)
// Mistake 2: using find() result without checking
let student = [].find((s) => s.id === 1);
// console.log(student.name); Error: student is undefined
if (student) {
console.log(student.name);
}
// Mistake 3: forgetting return in a callback with curly braces
// let result = numbers.find((n) => { n > 10 }); WRONG: no return, gives undefined
let result = numbers.find((n) => { return n > 10; }); // CORRECT
let short = numbers.find((n) => n > 10); // CORRECT (shorter)
// Mistake 4: sort() changes the original array
let original = [3, 1, 2];
let sorted = original.sort();
console.log(original); // [1, 2, 3] (changed!)
// Use toSorted() to keep the original safe
Quick Recap
- A callback is a function you give to an array method to run on each item
find()returns the first matching item,findIndex()returns its positionsome()checks if any item matches,every()checks if all items matchsort()needs a compare function for numbers and changes the original arraytoSorted()gives a sorted copy and keeps the original safeflat()merges nested arrays,fill()andArray.from()create arraysmap,filterandreduceare coming in the Advanced series
Awesome work! You now know the most useful JavaScript Array Methods. With these, you can search, check and organize data in a few lines instead of writing long loops.
Practice Exercises
- Create an array
[4, 9, 16, 25, 30]. Usefind()to get the first number above 10. - Use
findIndex()to find the position of the first even number in[3, 7, 8, 11, 12]. - Use
some()to check if an array of ages has anyone below 18. - Use
every()to check if all prices in an array are above 100. - Sort
[50, 8, 100, 23, 4]from small to big, then from big to small. - Sort an array of 4 name strings from A to Z.
- Flatten
[[1, 2], [3, [4, 5]], [6]]into one array. - Create an array of 10 zeros using
fill(). - Create the array
[1, 4, 9, 16, 25](squares) usingArray.from(). - Create an array of 4 book objects (title, price). Use
find()to get one book by title, and sort all books by price.
Assignment
Build an Employee Directory:
- Create an array of 6 employee objects with
id,name,department,salaryandisActive(true or false). - Create a function
getEmployeeById(id)usingfind()that returns the employee or the text “Employee not found”. - Create a function
hasHighEarner(limit)usingsome()that checks if any employee earns more than the limit. - Create a function
allActive()usingevery()that checks if all employees are active. - Create a function
removeEmployee(id)usingfindIndex()andsplice()that removes an employee and prints a message. If the id does not exist, print “Nothing to remove”. - Create a function
printBySalary()that prints all employees sorted from highest to lowest salary usingtoSorted()and a loop. - Test every function with at least 2 inputs.
Expected output example:
getEmployeeById(2) -> { id: 2, name: "Sara", ... }
getEmployeeById(99) -> Employee not found
hasHighEarner(100000) -> true or false (depends on your data)
removeEmployee(3) -> Removed: Bilal
removeEmployee(99) -> Nothing to remove
Bonus Challenge
Create a function groupByDepartment(employees) that returns an object where each key is a department name and each value is an array of employee names, for example { IT: ["Ali", "Sara"], HR: ["Bilal"] }. Hint: loop through the employees and use if (!result[dept]) result[dept] = []; before pushing.
What’s Next?
In the next tutorial, we will start the DOM section with JavaScript DOM Introduction. You will finally learn how JavaScript changes a real webpage, and your knowledge of JavaScript Array Methods will help you display and manage lists of data on the page.
Missed the last tutorial? Go back to JavaScript String Methods, or browse the full JavaScript Tutorial Series. For deeper reference, see the MDN Array reference.

