"Mastering JavaScript Array Methods for Web Development"

💡JavaScript Array Methods — Simplified! 🧩 1️⃣ map() Definition: Creates a new array by applying a function to each element of the original array. const nums = [1, 2, 3]; const doubled = nums.map(n => n * 2); console.log(doubled); // [2, 4, 6] 🧩 2️⃣ filter() Definition: Creates a new array with elements that pass the given test condition. const nums = [1, 2, 3, 4]; const even = nums.filter(n => n % 2 === 0); console.log(even); // [2, 4] 🧩 3️⃣ find() Definition: Returns the first element that satisfies the given condition. const nums = [5, 10, 15]; const found = nums.find(n => n > 8); console.log(found); // 10 🧩 4️⃣ findIndex() Definition: Returns the index of the first element that satisfies the condition. const nums = [3, 6, 9]; const index = nums.findIndex(n => n === 6); console.log(index); // 1 🧩 5️⃣ reduce() Definition: Executes a reducer function on each element, resulting in a single output value. const nums = [1, 2, 3, 4]; const sum = nums.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 10 🧩 6️⃣ join() Definition: Joins all elements of an array into a string. const words = ['JavaScript', 'is', 'awesome']; console.log(words.join(' ')); // "JavaScript is awesome" 🧩 7️⃣ split() Definition: Splits a string into an array based on a separator. const sentence = "Hello World"; console.log(sentence.split(' ')); // ['Hello', 'World'] 💬Try combining these methods for powerful one-liners! const result = [1,2,3,4,5].filter(n=>n%2===0).map(n=>n*10); console.log(result); // [20, 40] 💡JavaScript Array Methods in Action! Ever wondered how to turn objects into readable strings, split them back, or calculate totals easily? Here’s a simple example combining map(), join(), split(), and reduce(): const users = [   { id: 1, name: "Emma", age: 22, price: 200 },   { id: 2, name: "Max", age: 32, price: 300 },   { id: 3, name: "Olivia", age: 27, price: 500 },   { id: 4, name: "John", age: 28, price: 300 } ]; // ❌ join() works on arrays of strings, not objects. // ✅ So first, map() to get only names: const nameString = users.map(user => user.name).join(", "); console.log(nameString); // Output: "Emma, Max, Olivia, John" // ✅ split() works on strings, not arrays of objects: const nameArray = nameString.split(", "); console.log(nameArray); // Output: ["Emma", "Max", "Olivia", "John"] // ✅ reduce() to calculate total price: const total = users.reduce((sum, user) => sum + user.price, 0); console.log(total); // Output: 1300 🧠 What’s happening here? map() → Extracts only the names join() → Combines them into a single string split() → Converts the string back into an array reduce() → Sums up all prices #JavaScript #WebDevelopment #Coding Ajay Suneja 🇮🇳 ( Technical Suneja )

To view or add a comment, sign in

Explore content categories