Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Master Functional Array Methods for Clean Code

- 26.07.26 - ErcanOPAK

🧩 Map, Filter, Reduce = Functional JavaScript

Looping is imperative thinking. Functional methods transform data elegantly. Write cleaner, more declarative, and more testable code.

🔁 Array Transformation Patterns

// Real-world E-commerce Example
const orders = [
    { id: 1, customer: 'Alice', total: 150, status: 'completed' },
    { id: 2, customer: 'Bob', total: 75, status: 'pending' },
    { id: 3, customer: 'Charlie', total: 200, status: 'completed' },
    { id: 4, customer: 'Alice', total: 50, status: 'cancelled' },
    { id: 5, customer: 'Bob', total: 300, status: 'completed' }
];

// 1. Filter completed orders
const completed = orders.filter(o => o.status === 'completed');
console.log(completed.length); // 3

// 2. Map to get total amounts
const totals = orders.map(o => o.total);
console.log(totals); // [150, 75, 200, 50, 300]

// 3. Reduce to calculate total revenue
const revenue = orders
    .filter(o => o.status === 'completed')
    .reduce((sum, o) => sum + o.total, 0);
console.log(revenue); // 650

// 4. Group by customer
const customerOrders = orders.reduce((acc, o) => {
    acc[o.customer] = acc[o.customer] || [];
    acc[o.customer].push(o);
    return acc;
}, {});
console.log(customerOrders);
// {
//   Alice: [ { id: 1, total: 150, ... }, { id: 4, total: 50, ... } ],
//   Bob: [ { id: 2, total: 75, ... }, { id: 5, total: 300, ... } ],
//   Charlie: [ { id: 3, total: 200, ... } ]
// }

// 5. Customer spending summary
const customerSpending = orders
    .filter(o => o.status === 'completed')
    .reduce((acc, o) => {
        acc[o.customer] = (acc[o.customer] || 0) + o.total;
        return acc;
    }, {});
console.log(customerSpending);
// { Alice: 150, Bob: 300, Charlie: 200 }

🎯 Advanced Functional Patterns

// Data Processing Pipeline
const processOrderData = (orders) => 
    orders
        // Only completed orders
        .filter(order => order.status === 'completed')
        // Convert to summary objects
        .map(order => ({
            id: order.id,
            customer: order.customer.toUpperCase(),
            total: order.total,
            category: order.total > 100 ? 'Large' : 'Small'
        }))
        // Sort by total (descending)
        .sort((a, b) => b.total - a.total)
        // Add running total
        .reduce((acc, order, index, array) => {
            const runningTotal = array.slice(0, index + 1)
                .reduce((sum, o) => sum + o.total, 0);
            return [...acc, { ...order, runningTotal }];
        }, []);

// Performance Optimization: Single-pass processing
const processOrdersEfficiently = (orders) => {
    const result = [];
    let runningTotal = 0;
    const completed = orders.filter(o => o.status === 'completed');
    const sorted = [...completed].sort((a, b) => b.total - a.total);
    
    for (const order of sorted) {
        runningTotal += order.total;
        result.push({
            id: order.id,
            customer: order.customer.toUpperCase(),
            total: order.total,
            category: order.total > 100 ? 'Large' : 'Small',
            runningTotal
        });
    }
    return result;
};

// Custom Functional Utilities
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);

const getCompleted = arr => arr.filter(o => o.status === 'completed');
const getTotals = arr => arr.map(o => o.total);
const sum = arr => arr.reduce((s, v) => s + v, 0);

const getRevenue = pipe(getCompleted, getTotals, sum);
console.log(getRevenue(orders)); // 650

💡 Functional Programming Tips

  • Use filter before map to reduce processing
  • Chain methods for readability (but be mindful of performance)
  • Use reduce for complex accumulations
  • Keep functions pure (no side effects)
  • Use TypeScript for type safety with arrays

“Map, Filter, and Reduce changed how I think about data transformation. Once you master these patterns, you’ll write cleaner, more maintainable, and more testable code.”

— Senior Developer, Functional Programming Advocate

Related posts:

JavaScript: Fix Array.prototype.sort() Changing the Order of Equal-Looking Elements After a Browser ...

JavaScript: Fix Array.prototype.sort() Changing the Order of Equal-Looking Elements After a Browser ...

JavaScript: Fix a setTimeout Delay That Fires Immediately Because a Non-Numeric String Was Passed In...

JavaScript: Fix a setTimeout Delay That Fires Immediately Because a Non-Numeric String Was Passed In...

JavaScript: Use Async/Await for Clean Async Code

JavaScript: Use Async/Await for Clean Async Code

Views: 10

Post navigation

CSS: Create Realistic UI Depth with Advanced Box Shadow
AJAX: Build Robust REST APIs with Modern Design Patterns

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com