In JavaScript, we often work with Arrays (lists of items) and Objects (key-value pairs). JavaScript gives us built-in methods to manipulate data in arrays in a cleaner and more powerful way.
🔹 Arrays in JavaScript
An array is a list of values stored in a variable.
let numbers = [1, 2, 3, 4, 5];
🔹 Objects in JavaScript
An object is a collection of key-value pairs.
let person = {
name: "Alice",
age: 25,
city: "New York"
};
🔹 Common Array Methods
1. map()
👉 Used to transform each item in the array and return a new array.
let numbers = [1, 2, 3, 4];
// Multiply each number by 2
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
2. filter()
👉 Used to filter out elements based on a condition. Returns a new array with only elements that match.
let numbers = [1, 2, 3, 4, 5];
// Get only even numbers
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
3. reduce()
👉 Used to reduce an array to a single value (sum, product, etc.).
let numbers = [1, 2, 3, 4, 5];
// Sum of all numbers
let total = numbers.reduce((acc, num) => acc + num, 0);
console.log(total); // 15
🔹 Example Using Objects with These Methods
Let’s say we have an array of objects (like a list of users):
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 17 }
];
// 1. Get just the names (map)
let names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob", "Charlie"]
// 2. Filter adults (age >= 18)
let adults = users.filter(user => user.age >= 18);
console.log(adults);
// [{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }]
// 3. Get total age of all users (reduce)
let totalAge = users.reduce((sum, user) => sum + user.age, 0);
console.log(totalAge); // 72
✅ Summary
map()
→ transforms items in an array → returns a new arrayfilter()
→ selects items based on a condition → returns a new arrayreduce()
→ reduces array to a single value (sum, product, etc.)