JavaScript Tutorial in Hindi #18 | Array Iteration, Search & Transformation (2025)

1. Array Iteration with .forEach()

Used to loop through each item in an array.

js
CopyEdit
let fruits = ["Apple", "Banana", "Mango"];

fruits.forEach(function(fruit, index) {
console.log(`${index + 1}. ${fruit}`);
});

2. Transforming Arrays with .map()

Creates a new array by applying a function to every item.

js
CopyEdit
let numbers = [1, 2, 3];
let squares = numbers.map(num => num * num);

console.log(squares); // [1, 4, 9]

3. Filtering Arrays with .filter()

Returns a new array with items that match a condition.

js
CopyEdit
let ages = [12, 18, 25, 30];
let adults = ages.filter(age => age >= 18);

console.log(adults); // [18, 25, 30]

4. Finding Items with .find() & .indexOf()

🔸 .find()

Returns the first matching item.

js
CopyEdit
let users = ["John", "Alice", "Mohit"];
let result = users.find(user => user.startsWith("M"));

console.log(result); // "Mohit"

🔸 .indexOf()

Returns the index of an item (or -1 if not found).

js
CopyEdit
let colors = ["Red", "Green", "Blue"];
console.log(colors.indexOf("Green")); // 1

5. Sorting Arrays with .sort()

Sorts elements in alphabetical or numerical order.

🔸 Sorting Strings:

js
CopyEdit
let names = ["Zara", "Alex", "John"];
names.sort();
console.log(names); // ["Alex", "John", "Zara"]

🔸 Sorting Numbers (needs a compare function):

js
CopyEdit
let nums = [10, 5, 20];
nums.sort((a, b) => a - b);
console.log(nums); // [5, 10, 20]

6. Practice Example

👇 Task: From an array of students, get names of those with marks > 75, and return them in uppercase sorted order.

js
CopyEdit
let students = [
{ name: "John", marks: 80 },
{ name: "Alice", marks: 60 },
{ name: "Mohit", marks: 90 },
{ name: "Rita", marks: 70 }
];

let topStudents = students
.filter(student => student.marks > 75)
.map(student => student.name.toUpperCase())
.sort();

console.log(topStudents); // ["JOHN", "MOHIT"]