Tips for creating a high-performing algorithm to locate a specific word within a JSON file

I am in the process of creating a word game that involves users typing letters on a board to form meaningful words. If the typed word matches any word in a JSON file, the user earns a point. I have successfully implemented the basic functionalities of the game. However, I have encountered an issue with my linear algorithm when trying to search through approximately 400k words in the JSON file. Can anyone suggest a more efficient algorithm for this task? Below is a glimpse of how the interface looks - random letters appearing on the board.

https://i.sstatic.net/B5oSR.png

Here is a snippet from my JSON file:

{"a": 1, "aa": 1, "aaa": 1, ...

This is how my JavaScript code currently appears:

 document.getElementById('button').addEventListener('click', loadData);

    const letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',
'p','q','r','s','t','u','v','w','x','y','z'];

    var searched_word = '';

    var boxes = document.querySelectorAll('.square');

    function clickBox() {
      boxes.forEach(function(box) {
        box.addEventListener('click', function(e) {
          e.preventDefault();
          searched_word += this.innerHTML;
          document.querySelector('.input').value = searched_word;
        });
      });
      return searched_word;
    }

    function randomLetters(boxes) {
      for (var i = 0; i < boxes.length; i++) {
        let randomLetterNumber = Math.floor(Math.random() * letters.length);
        boxes[i].innerHTML = letters[randomLetterNumber].toLocaleUpperCase();
      }
    }

    function loadData() {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', 'words_dictionary_full.json', true);
      xhr.onload = function() {
        if (this.status === 200) {
          const words = JSON.parse(this.responseText);
          for (word in words) {
            if (word === clickBox().toLowerCase()) {
              console.log('true');
            } else {
              console.log('false');
            }
          }
        }
      };
      xhr.send();
    }

    clickBox();
    randomLetters(boxes);

Answer №1

To efficiently search for words in an array, you can first sort the array alphabetically in your database or JSON file. Once sorted, you can implement a binary search algorithm.

Here is an example implementation of a binary search algorithm (source):

/** 
* Copyright 2009 Nicholas C. Zakas. All rights reserved.
* MIT-Licensed
* Uses a binary search algorithm to locate a value in the specified array. 
* @param {Array} items The array containing the item. 
* @param {variant} value The value to search for. 
* @return {int} The zero-based index of the value in the array or -1 if not found. 
*/
function binarySearch(items, value){
    var startIndex  = 0,
        stopIndex   = items.length - 1,
        middle      = Math.floor((stopIndex + startIndex)/2);

    while(items[middle] !== value && startIndex < stopIndex){

        //adjust search area
        if (value < items[middle]){
            stopIndex = middle - 1;
        } else if (value > items[middle]){
            startIndex = middle + 1;
        }

        //recalculate middle
        middle = Math.floor((stopIndex + startIndex)/2);
    }

    //check if it's the right value
    return (items[middle] !== value) ? -1 : middle;
}

Simply provide the list of words and the word you want to search as parameters. If the entry does not exist in the list, the function will return -1. You can utilize Object.keys(json) to convert the keys of a JSON object into an array of words for the items parameter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using conditional rendering within the map function in React

I am working with the code snippet below and I am looking to implement a conditional rendering to exclude index 0 from being displayed. How can I achieve this? return ( <section> {pokemonCards.map((pokemon, index) => ...

Tips for maintaining a user's session post-login with Passport and Express JS

I recently set up a node backend using express and integrated Passport for authentication purposes. My application has a route called /login for logging in and another route called /me to retrieve information about the currently logged in user. Below is t ...

Why is it necessary to omit node_modules from webpack configuration?

Check out this webpack configuration file: module.exports = { mode: "development", entry: "./src/index.ts", output: { filename: "bundle.js" }, resolve: { extensions: [".ts"] }, module: { rules: [ { test: /\.ts/ ...

Creating separate chunks for individual files in Vue CLI3JsonPropertyTitleFileType

I am working on a project using vue-cli3 and need to separate out a specific file for chunking due to IIS requirements. Currently, webpack chunks files based on default settings and also automatically creates chunks from dynamic imports in vue-router. How ...

What is the best method for retrieving a child control from a TR element?

I am facing an issue with a hidden field inside each Tr in my template: <ItemTemplate> <tr style="" class="ui-selectee trClass ui-widget-content"> <td style="width: 100px"> <asp:HiddenField ID="idField" runat=" ...

Limit express to only allow AJAX requests

Currently working on an Express app where I aim to restrict access to the routes exclusively through AJAX requests. Aware that this involves using the X-Requested-With header, but uncertain of how to globally block other request types. Any suggestions or ...

Using an action code to retrieve the current user from firebase: A step-by-step guide

I am in the process of designing 2 registration pages for users. The initial page prompts the user to input their email address only. After they submit this information, the following code is executed: await createUserWithEmailAndPassword(auth, email.value ...

When requesting a Node.js API from Javascript fetch, the session custom property is throwing an undefined error

I am currently working on a User Login Project, where the APIs are built using Node.js and Express. The UI part is developed using HTML and JavaScript, with these components existing as separate projects. Upon user login, a fetch call is made in JavaScrip ...

What strategies can I use to organize and fuse together my library?

I am intrigued by the concept of modular JS and have decided to create my own small library to experiment with it. Here is my vision for how I want it to function: It will include 5 methods Users can download a full library that exports a global variab ...

JavaScript error: forEach is not a function

I've encountered an issue while attempting to loop through a JSON object to extract data. Whenever I run my code, I receive this error: Type Error: element.listing.forEach is not a function. It's worth mentioning that I've used this method ...

Using JavaScript functions to modify the style of the DOM

Is there a way to change the style of a dom element using JavaScript when only the element id and style value are passed as parameters, without passing the actual style parameter itself? For example, is it possible to use the id "first" and set the color ...

Submitting buttons by using a textbox array is a simple process

I need help figuring out why my buttons are not working on a page I'm creating with around 300 textboxes generated from a foreach loop. While I've successfully been able to write links into the textboxes, I am struggling to read the textboxes arr ...

The ng-click event in AngularJS does not function as expected when nested within another ng-repeat loop

I am facing an issue with ng-click in my Angular application (version 1.0.4). The first ng-click works fine, but the second one does not. <div class="menu-group" ng-repeat="module in modules"> <div ng-click="toggle($event, $parent)" ...

Is there a way to prevent a 'keyup' event from being triggered by a 'keydown' event?

I have a tool that resolves zip codes and I am currently utilizing a keyup event handler to trigger a server query once the input length reaches 5 characters. However, I want to prevent unnecessary calls to the script, so I am exploring the possibility o ...

Insert newly added rows' values into the database dynamically

Hello there, I'm currently working on a PHP form that needs to dynamically add a table row when the "Add" button is pressed. I'm using a for loop to save the values, but I'm running into an issue where the data is not being saved into my dat ...

does not output any console log statements

I am attempting to showcase the values of checkboxes on the console, however, it is not working. <input type="checkbox" id="id_price" value="1" onclick="display_img()">Under £200<br> <input type="checkbox" id="id_pr ...

Tips for creating a curved shape using fabric.js

I am encountering an issue while trying to draw an arc using a circle with a start and end angle in my code. Here is the snippet I am working with: var circle = new fabric.Circle({ radius: 30, left: 20, top: 20, fill: " ...

Ways to locate two div class elements that are generated dynamically

I am looking to dynamically create 2 divs in different locations. One for displaying information and another for editing information. I want to be able to delete both divs with the same class when using the delete button. Since they are located in differe ...

Differences Between DOM and Refs in React

When it comes to React, what distinguishes the use of DOM from Refs? While it is possible to utilize typical JavaScript DOM node selectors in React for targeting specific elements, refs also offer a way to achieve the same functionality. What are the adv ...

The request cannot be completed using GET. The connection has not been established, and the offline queue is not activated

Encountering this unexpected error in the live environment, despite implementing a retry strategy of 500ms and wrapping the setAsync and getAsync functions with a setTimeout of 1s. It's puzzling why this issue persists. Error Message: AbortError at ...