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: Build Search Engine with Array Methods

- 25.07.26 - ErcanOPAK

🔍 Client-Side Search = Instant Results

Users expect instant search results. JavaScript array methods enable fast client-side search with fuzzy matching and filtering.

📝 Search Engine Implementation

class SearchEngine {
    constructor(data, options = {}) {
        this.data = data;
        this.options = {
            keys: options.keys || ['title', 'description'],
            threshold: options.threshold || 0.3,
            maxResults: options.maxResults || 50,
            caseSensitive: options.caseSensitive || false
        };
    }

    search(query) {
        if (!query || query.trim().length === 0) {
            return [];
        }

        const searchTerm = this.options.caseSensitive 
            ? query.trim() 
            : query.trim().toLowerCase();

        const results = this.data
            .map(item => ({
                item,
                score: this.calculateScore(item, searchTerm)
            }))
            .filter(result => result.score > 0)
            .sort((a, b) => b.score - a.score)
            .slice(0, this.options.maxResults)
            .map(result => ({
                ...result.item,
                _score: result.score
            }));

        return results;
    }

    calculateScore(item, searchTerm) {
        let totalScore = 0;
        const searchWords = searchTerm.split(' ');

        for (const key of this.options.keys) {
            const value = this.getValue(item, key);
            if (!value) continue;

            const text = this.options.caseSensitive 
                ? value 
                : value.toLowerCase();

            if (text === searchTerm) {
                totalScore += 100;
            }

            if (text.includes(searchTerm)) {
                totalScore += 50;
            }

            const words = text.split(' ');
            for (const word of searchWords) {
                if (words.some(w => w.includes(word))) {
                    totalScore += 10;
                }
            }

            if (text.startsWith(searchTerm)) {
                totalScore += 30;
            }

            const distance = this.levenshteinDistance(text, searchTerm);
            const maxLength = Math.max(text.length, searchTerm.length);
            if (maxLength > 0) {
                const similarity = 1 - (distance / maxLength);
                if (similarity > this.options.threshold) {
                    totalScore += similarity * 20;
                }
            }
        }

        return totalScore;
    }

    getValue(item, path) {
        return path.split('.').reduce((obj, key) => 
            obj && obj[key] !== undefined ? obj[key] : null, item
        );
    }

    levenshteinDistance(str1, str2) {
        if (str1.length === 0) return str2.length;
        if (str2.length === 0) return str1.length;

        const matrix = [];
        for (let i = 0; i <= str1.length; i++) {
            matrix[i] = [i];
        }
        for (let j = 0; j <= str2.length; j++) {
            matrix[0][j] = j;
        }

        for (let i = 1; i <= str1.length; i++) {
            for (let j = 1; j <= str2.length; j++) {
                const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
                matrix[i][j] = Math.min(
                    matrix[i - 1][j] + 1,
                    matrix[i][j - 1] + 1,
                    matrix[i - 1][j - 1] + cost
                );
            }
        }

        return matrix[str1.length][str2.length];
    }

    getSuggestions(query, limit = 5) {
        if (!query || query.trim().length === 0) {
            return [];
        }

        const suggestions = new Set();
        const searchTerm = query.trim().toLowerCase();

        for (const item of this.data) {
            for (const key of this.options.keys) {
                const value = this.getValue(item, key);
                if (!value) continue;

                const text = value.toLowerCase();
                if (text.includes(searchTerm)) {
                    const words = text.split(' ');
                    for (const word of words) {
                        if (word.toLowerCase().includes(searchTerm) 
                            && word.length > 2) {
                            suggestions.add(word);
                        }
                    }
                }
            }

            if (suggestions.size >= limit * 2) break;
        }

        return Array.from(suggestions).slice(0, limit);
    }
}

const products = [
    { id: 1, title: 'Wireless Headphones', category: 'Electronics', price: 99 },
    { id: 2, title: 'Smart Watch', category: 'Electronics', price: 199 },
    { id: 3, title: 'Running Shoes', category: 'Sports', price: 89 },
    { id: 4, title: 'Coffee Mug', category: 'Kitchen', price: 15 },
    { id: 5, title: 'Backpack', category: 'Fashion', price: 45 }
];

const searchEngine = new SearchEngine(products, {
    keys: ['title', 'category'],
    threshold: 0.2,
    maxResults: 10
});

const debounce = (fn, delay) => {
    let timeout;
    return (...args) => {
        clearTimeout(timeout);
        timeout = setTimeout(() => fn(...args), delay);
    };
};

const performSearch = debounce((query) => {
    const results = searchEngine.search(query);
    const suggestions = searchEngine.getSuggestions(query);
    
    renderResults(results);
    renderSuggestions(suggestions);
}, 300);

🎯 Performance Optimization

class SearchIndex {
    constructor(data, keys) {
        this.index = new Map();
        this.data = data;
        this.keys = keys;
        this.buildIndex();
    }

    buildIndex() {
        for (const item of this.data) {
            for (const key of this.keys) {
                const value = this.getValue(item, key);
                if (!value) continue;

                const words = value.toLowerCase().split(' ');
                for (const word of words) {
                    if (!this.index.has(word)) {
                        this.index.set(word, []);
                    }
                    if (!this.index.get(word).includes(item)) {
                        this.index.get(word).push(item);
                    }
                }
            }
        }
    }

    search(query) {
        const words = query.toLowerCase().split(' ');
        const results = [];
        const seen = new Set();

        for (const word of words) {
            const items = this.index.get(word) || [];
            for (const item of items) {
                if (!seen.has(item)) {
                    seen.add(item);
                    results.push(item);
                }
            }
        }

        return results;
    }

    getValue(item, path) {
        return path.split('.').reduce((obj, key) => 
            obj && obj[key] !== undefined ? obj[key] : null, item
        );
    }
}

💡 Search Optimization Tips

  • Build search index for faster lookups
  • Use debouncing for instant search
  • Implement fuzzy matching for typos
  • Provide auto-complete suggestions
  • Use Web Workers for large datasets

Client-side search with fuzzy matching creates a delightful user experience. Instant results and intelligent suggestions make users feel understood.

— Frontend Developer

Related posts:

Javascript Refresh and CountDown Timer

Javascript Refresh and CountDown Timer

JavaScript: Master Promises for Async Operations

JavaScript: Master Promises for Async Operations

How replace characters with asterisks (*) except first characters

How replace characters with asterisks (*) except first characters

Views: 8

Post navigation

HTML: Build Accessible Navigation with Semantic Elements
AJAX: Implement API Versioning Strategies

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 (980)
  • 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 (980)
  • 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