JavaScript Arrays & Objects: Mastering map, filter, reduce

JavaScript Arrays, Objects & Array Methods Understanding how arrays and objects work helps you organize, transform, and analyze data in JavaScript. Here's a quick and clear breakdown: *1️⃣ Arrays in JavaScript* An array stores a list of values. ```js let fruits = ["apple", "banana", "mango"]; console.log(fruits[1]); // banana ``` ▶️ This creates an array of fruits and prints the second fruit (`banana`), since arrays start at index 0. *2️⃣ Objects in JavaScript* Objects hold key–value pairs. ```js let user = { name: "Riya", age: 25, isAdmin: false }; console.log(user.name); // Riya console.log(user["age"]); // 25 ``` ▶️ This object represents a user. You can access values using dot (`.`) or bracket (`[]`) notation. *3️⃣ Array Methods – map, filter, reduce* 🔹 *map()* – Creates a new array by applying a function to each item ```js let nums = [1, 2, 3]; let doubled = nums.map(n => n * 2); console.log(doubled); // [2, 4, 6] ``` ▶️ This multiplies each number by 2 and returns a new array. 🔹 *filter()* – Returns a new array with items that match a condition ```js let ages = [18, 22, 15, 30]; let adults = ages.filter(age => age >= 18); console.log(adults); // [18, 22, 30] ``` ▶️ This filters out all ages below 18. 🔹 *reduce()* – Reduces the array to a single value ```js let prices = [100, 200, 300]; let total = prices.reduce((acc, price) => acc + price, 0); console.log(total); // 600 ``` ▶️ This adds all prices together to get the total sum. *💡 Extra Notes:* • `map()` → transforms items • `filter()` → keeps matching items • `reduce()` → combines all items into one result 🎯 *Practice Challenge:* • Create an array of numbers • Use `map()` to square each number • Use `filter()` to keep only even squares • Use `reduce()` to add them all up

To view or add a comment, sign in

Explore content categories