JavaScript has got more expressive - reduce vs Object.groupBy for group data. For years, we used reduce(), when we wanted to group data. It worked. It was powerful. But it wasn't always readable. → The old way with reduce() const grouped = users.reduce((acc, user) => { const key = user.role; (acc[key] ||= []).push(user); return acc; }, {}); recude() is a general-purpose accumulator. We used it for grouping because we didn't have native alternative. → The native Object.groupBy()approach. const grouped = Object.groupBy(users, user => user.role); Same result. Much clearer code. Now the code says exactly what it does. - Less boilerplate. - More declarative. - Easier for teams to maintain. → The real win This isn’t about fewer lines it’s about readability, consistency, and maintainability at scale. → Use: - groupBy() → for grouping - reduce() → for true aggregation / complex transformations Your future teammates will thank you. Have you started switching to Object.groupBy() yet? 👀 #JavaScript #CleanCode #WebDevelopment #DeveloperExperience #SoftwareEngineering
JavaScript: Reduce vs Object.groupBy for Grouping Data
More Relevant Posts
-
JavaScript Data Structures Roadmap 🔥 Mastering Data Structures is what separates "coders" from "engineers." In JavaScript, understanding how to manage memory and organize data efficiently is crucial for building high-performance applications. Here is your step-by-step roadmap to conquering Data Structures in JS: 1. The Foundations (Basics) Before coding, you must understand the "Why" and "How." • Big O Notation: Learn to analyze Time and Space complexity. • Memory Management: How JS handles the Stack vs. the Heap. • Pointers & References: Understanding how objects are stored in memory. 2. Linear Data Structures The building blocks of most applications. • Arrays: Beyond basic methods understand insertions, deletions, and search complexities. • Linked Lists: Implement Singly, Doubly, and Circular linked lists. • Stacks & Queues: Master LIFO (Last-In-First-Out) and FIFO (First-In-First-Out) logic. 3. Non-Linear Structures Level up to handle complex data relationships. • Hash Tables: Objects and Maps in JS. Learn about collision handling. • Trees: Binary Search Trees (BST), Heaps (Min/Max), and Tries (Prefix Trees). • Graphs: Representations (Adjacency List/Matrix) and Traversal (DFS & BFS). 4. Advanced Concepts & Practice • Custom Implementation: Don't just use Array.push(); try to build your own Stack or Linked List class from scratch. • Real-World Projects: Use a Graph to build a social network "friend" feature or a Tree for a file directory system. • Algorithmic Challenges: Consistent practice on LeetCode or HackerRank to sharpen your problem-solving muscle. Consistency is the key. If you master these, you can pick up any framework in days. For help and guidance in you carrier path https://lnkd.in/gH3paVi7 Join my dev community for resources📚, tech talks🧑🏻💻and learning 🧠 https://lnkd.in/gt8WeZSt #JavaScript #DataStructures #DSA #WebDevelopment #SoftwareEngineering #CodingLife #RohanKumar
To view or add a comment, sign in
-
-
🚀 Why I replaced Object with Map() in a performance-critical backend feature I was working on a feature where I needed to track active driver sessions in memory. Initially, I used a normal Object: const sessions = {}; sessions[101] = { status: "online" }; sessions[102] = { status: "offline" }; It worked well… until the number of active sessions grew to thousands. Frequent insertions, deletions, and lookups started becoming harder to manage efficiently. That’s when I switched to Map(). 📌 What is Map()? Map is a built-in JavaScript data structure designed for efficient key-value storage with faster and predictable performance. 📌 How to create Map()? Map can be created using the Map constructor. const sessions = new Map(); 📌 Operations with Time Complexity sessions.set(101, { status: "online" }); // Insert → O(1) sessions.get(101); // Lookup → O(1) sessions.has(101); // Check → O(1) sessions.delete(101); // Delete → O(1) All major operations in Map are O(1) average time complexity, making it ideal for high-performance systems. 📌 Why use Map instead of Object? • Faster insert and lookup → O(1) • Maintains insertion order • Supports any data type as key • Optimized for frequent add/remove operations • Better performance for large datasets 📌 Real-world backend use cases • Caching user sessions • Managing socket connections • Storing in-memory lookup tables • Deduplication logic • Tracking active users 📌 Object vs Map (Performance Insight) Object → Not optimized for frequent insert/delete Map → Designed for high-performance key-value operations Map internally uses a hash table, enabling constant-time operations. 💡 Key Lesson Choosing the right data structure can significantly improve performance. Map provides predictable O(1) performance, making it a powerful tool for scalable backend systems. #JavaScript #NodeJS #BackendEngineering #SoftwareEngineering #Programming #Performance
To view or add a comment, sign in
-
-
A common TypeScript anti-pattern I keep seeing. When working with nested arrays, many developers lean on optional chaining everywhere, especially inside loops. It feels safe. It feels concise. But it quietly introduces unnecessary branching and noisy logic. --- 🛡️ The “defensive everywhere” approach ``` function getActiveEmails(data?: ApiResponse) { return data?.users ?.filter(u => u?.isActive) ?.map(u => u?.profile?.email ?? "no-email") ?? []; } ``` What’s happening here? - "data?.users" → branch - "u?.isActive" → branch per iteration - "u?.profile?.email" → multiple branches per iteration - "?? []" → fallback branch You’ve now created a combinatorial explosion of paths inside what should be a simple transformation. Your tests? They now need to cover: - missing "data" - missing "users" - partially invalid users - missing profiles - missing emails All implicitly baked into one chain. --- ✅ Early return & controlled assumptions ``` function getActiveEmails(data?: ApiResponse) { if (!data?.users) return []; return data.users .filter(user => user.isActive) .map(user => user.profile.email); } ``` Key differences: - The guard ("if") still uses optional chaining, but only once, at the boundary - Inside the loop, we treat data as valid by contract - No defensive noise inside "filter"/"map" - The “happy path” is clean and linear --- Why? Optional chaining inside iteration is especially costly: - It introduces branches per element - It hides data contract issues - It bloats test cases unnecessarily - It makes bugs harder to spot (everything just becomes “undefined”) --- So, - Use optional chaining at the edges of your system - Use early returns to establish guarantees - Keep your core logic branch light and explicit --- Optional chaining isn’t the problem. Unstructured defensiveness is. #TypeScript #JavaScript #CleanCode #CodeQuality #Refactoring #BestPractices #DeveloperTips
To view or add a comment, sign in
-
𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗖𝗼𝗿𝗲 𝗥𝗲𝗮𝗰𝘁 𝗛𝗼𝗼𝗸𝘀 You can build simple, reusable functions with React Hooks. They replaced class components as the standard way to write React. Here are some key hooks: - useState: stores local component state - useEffect: runs code after render - useContext: shares data globally across your component tree - useReducer: manages complex state logic - useRef: holds a mutable value that persists between renders React Hooks must follow strict rules to avoid bugs and performance issues. You can use custom hooks to extract and reuse stateful logic across multiple components. They are JavaScript functions that start with 'use' and can call other hooks. Some popular custom hooks include: - useFetch: reusable data fetching - useDebounce: optimized search input - useToggle: reusable boolean toggle - useAuth: authentication state React relies on the order in which hooks are called being stable between renders. Breaking these rules causes subtle bugs that are hard to track down. Source: https://lnkd.in/eiCg_sgR Optional learning community: https://lnkd.in/gd7zJNkC
To view or add a comment, sign in
-
🚀 Stop the Spread: Why TypeScript is Saving Your Production Database We’ve all been there: You’ve built your schema, your logic feels sound, and you’re ready to ship. Then... the red squiggly line appears. 🛑 I recently spent some time debugging a prisma.doctor.create() call that reminded me exactly why strict typing is a developer's best friend—even when it feels like a hurdle. The "Spread Trap" 🪤 I was using the JavaScript spread operator ...payload to pass data into Prisma. It’s clean, it’s modern, and in this case, it was completely hiding the bugs. The Culprits 🔍 After digging into the generated DoctorCreateInput types, I found three silent killers: Case Sensitivity: I passed currentWorkplace, but Prisma demanded currentWorkPlace (Spot the capital 'P'!). Missing Requirements: My payload was missing a required description field defined in my .prisma schema. Type Mismatches: Using ...spread meant TypeScript couldn't warn me that my incoming interface didn't perfectly align with my DB model. The Code: Before vs. After 💻 ❌ THE BUGGY WAY (The Spread Trap) TypeScript // Error: Type mismatch and missing required fields const doctor = await tx.doctor.create({ data: { ...payload.doctor, // Casing mismatch hidden here userId: userData.user.id, } }); ✅ THE ROBUST WAY (Explicit Mapping) TypeScript // Explicit mapping ensures 100% schema alignment const doctor = await tx.doctor.create({ data: { name: payload.doctor.name, email: payload.doctor.email, currentWorkPlace: payload.doctor.currentWorkplace, // Fixed casing description: payload.doctor.description || "", // Added requirement userId: userData.user.id, // Now TypeScript is happy! } }); The Takeaway 💡 Prisma types are unforgiving for a reason. They ensure that what hits your database is exactly what you intended. My new rule: Use spread for quick drafts, but use Explicit Mapping for production-grade services. It’s better to fix a type error in your IDE than a 500 Internal Server Error in production. #WebDevelopment #TypeScript #Prisma #Backend #NodeJS #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
✨ 𝗗𝗮𝘆 𝟭𝟮 𝗼𝗳 𝗠𝘆 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 🚀 Today I explored powerful 𝗔𝗿𝗿𝗮𝘆 𝗠𝗲𝘁𝗵𝗼𝗱𝘀 𝗮𝗻𝗱 𝘁𝗵𝗲 𝗱𝗮𝘁𝗮 𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝘀 𝗦𝗲𝘁 & 𝗠𝗮𝗽. 🔹 Practiced array methods like 𝗺𝗮𝗽(), 𝗳𝗶𝗹𝘁𝗲𝗿(), 𝗿𝗲𝗱𝘂𝗰𝗲(), 𝗳𝗼𝗿𝗘𝗮𝗰𝗵() — making data transformation cleaner and more functional. 🔹 Learned how 𝗦𝗲𝘁 stores unique values. 🔹 Understood how 𝗠𝗮𝗽 stores key-value pairs with better flexibility than plain objects. It’s amazing how these built-in structures make handling data more efficient and readable. Step by step, strengthening my JavaScript fundamentals 💪 #JavaScript #100DaysOfCode #WebDevelopment #LearningJourney #FrontendDevelopment #DataStructures
To view or add a comment, sign in
-
-
Non-primitive data types Most JavaScript beginners learn numbers and strings first… But real power starts with non-primitive data types. 🚀 If you want to build real applications, you must understand these. In JavaScript, non-primitive data types can store multiple values and complex data. Here are the most important ones: • Object – Stores data in key–value pairs. Perfect for real-world data like users, products, or settings. • Array – Stores a list of values in a single variable. Great for lists like items, users, or tasks. • Function – A reusable block of code that performs a task. Functions are also treated as objects in JavaScript. • Date, Map, Set – Special objects used for managing time, unique values, and key-value collections. ✨ Key idea: Unlike primitive types, non-primitive types are stored by reference, which changes how copying and comparison work. Master these and your JavaScript skills will level up quickly. #JavaScript #WebDevelopment #FrontendDevelopment #ProgrammingBasics #LearnToCode #SoftwareDevelopment #JavaScriptTips #CodingForBeginners #FullStackDevelopment #TechEducation
To view or add a comment, sign in
-
-
Early on, we’ve all written that routes.js file. You know the one. Business logic, Joi validations, database queries, and error handling—all stuffed into one massive functional callback. It works perfectly fine for a quick MVP. But when the application scales, it becomes a nightmare to maintain, debug, and test. Moving to class-based controllers—specifically using a framework like Hapi—completely changes the way you look at Node.js architecture. Here is why making the shift to structured, object-oriented patterns is worth the effort: 1. True Separation of Concerns: Your route file simply maps endpoints to controller methods. The controller handles the request/response lifecycle, and the heavy lifting is pushed down to your service layer. 2. Dependency Injection: Class constructors make it incredibly easy to inject your database instances (like Postgres) or external services. Your code becomes modular and completely decoupled. 3. Painless Unit Testing: Because dependencies are injected through the constructor, mocking them out for unit tests takes seconds. No more wrestling with complicated proxy tools just to isolate a function. 4. Readability: When a new engineer jumps into the codebase, they don't have to untangle a web of nested functions. The architecture is predictable. Functional programming in JavaScript is great, but for structured, robust backend systems, class-based architectures bring a level of sanity and predictability that is hard to beat. Curious to hear from other backend folks—are you team functional routes or team class-based controllers? Let me know below! 👇 #nodejs #hapijs #backendengineering #softwarearchitecture
To view or add a comment, sign in
-
Do you know how Promise.all() works in JavaScript? The more I build, the more I realize how much there is to learn. Recently, I was working with Supabase as my database to store both default events and user-created events. I needed to fetch data from two tables and combine them. My initial approach looked like this: const { data } = await supabase.from("eventchosen_duplicate").select("*"); const { data: eventDefault } = await supabase.from("eventchosen").select("*"); setAllEvents([...data, ...eventDefault]); The issue here is that each await runs sequentially, meaning the second request waits for the first one to finish. A better approach is using Promise.all(): const [duplicateRes, defaultRes] = await Promise.all([ supabase.from("eventchosen_duplicate").select("*"), supabase.from("eventchosen").select("*"), ]); This runs both requests in parallel, improving performance. Small improvement, big lesson: Better async patterns lead to better performance. Still building. Still learning. #JavaScript #React #Supabase #WebDevelopment #FrontendDevelopment #learnInPublic
To view or add a comment, sign in
-
-
🚀 𝐖𝐡𝐲 .𝐦𝐚𝐩() 𝐢𝐬 𝐭𝐡𝐞 𝐇𝐞𝐚𝐫𝐭 𝐨𝐟 𝐌𝐨𝐝𝐞𝐫𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 If you are still using for loops to transform data, you are writing more code than you need to. In modern development—especially within frameworks like 𝐑𝐞𝐚𝐜𝐭, 𝐕𝐮𝐞, and 𝐀𝐧𝐠𝐮𝐥𝐚𝐫—the .map() method is the gold standard for clean, predictable data transformation. 💡 𝐓𝐡𝐞 𝐂𝐨𝐫𝐞 𝐁𝐞𝐧𝐞𝐟𝐢𝐭𝐬: 𝟏. 𝐃𝐞𝐜𝐥𝐚𝐫𝐚𝐭𝐢𝐯𝐞, 𝐧𝐨𝐭 𝐈𝐦𝐩𝐞𝐫𝐚𝐭𝐢𝐯𝐞: Instead of telling the computer how to loop (index counters, increments), you tell it what you want the result to be. 𝟐. 𝐏𝐮𝐫𝐞 𝐈𝐦𝐦𝐮𝐭𝐚𝐛𝐢𝐥𝐢𝐭𝐲: Unlike .forEach(), .map() does not mutate the original array. It returns a brand-new array, which is crucial for state management and avoiding side-effect bugs. 𝟑. 𝐂𝐡𝐚𝐢𝐧𝐚𝐛𝐢𝐥𝐢𝐭𝐲: Because it returns an array, you can immediately chain it with .filter() or .reduce() for powerful, one-line data pipelines. 🛠 𝐓𝐡𝐞 𝐕𝐢𝐬𝐮𝐚𝐥 𝐃𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐜𝐞: ❌ 𝐓𝐡𝐞 𝐎𝐥𝐝 𝐖𝐚𝐲 (𝐅𝐨𝐫 𝐋𝐨𝐨𝐩): let doubled = []; for (let i = 0; i < numbers.length; i++) { doubled.push(numbers[i] * 2); } ✅ 𝐓𝐡𝐞 𝐌𝐨𝐝𝐞𝐫𝐧 𝐖𝐚𝐲 (.𝐦𝐚𝐩): const doubled = numbers.map(num => num * 2); 🌟 𝐏𝐫𝐨 𝐓𝐢𝐩: When using .map() in React to render lists, always remember to include a unique 𝐤𝐞𝐲 prop. This allows the Virtual DOM to track changes efficiently and boosts performance. Stop managing loops and start transforming data. Your future self (and your code reviewers) will thank you. 💻✨ Feel free to reach me out for any career guidance Naveen .G.R|CareerByteCode #JavaScript #WebDevelopment #ReactJS #CodingTips #SoftwareEngineering #CleanCode #ProgrammingLife
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development