Difficulty in finding and retrieving array indexes that match a specific character pattern

Is it possible to return indexes from an array based on a search term, regardless of the order of characters in the array?

const array = ['hell on here', '12345', '77788', 'how are you llo'];

function findMatchingIndexes(arr, searchTerm) {
    const indexArray = [];

    for(let i = 0; i < arr.length; i++) {
        if (searchTerm.charAt(i) <= arr.indexOf(i)) {
            indexArray.push(i);
        }
    }

    return indexArray;
}

document.write(findMatchingIndexes(array, "hello"));

This code should output 0 and 3 as the matching indexes in the array. How would you approach this problem?

Answer №1

For those employing jQuery, the grep function could potentially be beneficial. You can learn more about it by visiting this link.

Answer №2

Check out this code snippet:

function characterMatch(arr, search) {
    var output = [],
        itemSplit,
        charFound = false;

    // Loop through each item in the array
    for (var i = 0; i<arr.length; i++) {
        charFound = false;
        // Create an array of characters from the current item
        itemSplit = arr[i].split('');
        // Iterate over every character in 'search' string
        for (var j = 0; j<search.length; j++) {
            charFound = false;
            // Iterate over each character in the split array of characters
            for (var k=0; k<itemSplit.length; k++) {
              // If there is a match, set flag to true and exit loop
              if (search.charAt(j) === itemSplit[k]) {
                charFound = true;
                break;
              }
            }
            // If character not found, then break loop
            if (!charFound) {
                break;
            }
            // Remove first character to avoid re-matching
            itemSplit.shift();
        }
        // If 'charFound' is still true by now, it means all chars have been matched
        if (charFound) {
            // Add the current index to the result array
            output.push(i);
        }
    }
    return output;
}

characterMatch(['hello world', '12345', '88999', 'how are you'], 'hello');

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

Angular applications with separate, autonomous routers

Imagine having a massive enterprise application divided into multiple independent submodules (not to be confused with angular modules). I prefer not to overwhelm the routing in a single location and wish for these autonomous modules (non-angular modules) ...

Navigating the intricacies of handling login with ajax

Essentially, the process of logging in typically unfolds as follows: The user inputs their information into the login form and submits it, The server (whether it be Ruby, PHP, Node.js, or any other) processes this data and either, a) redirects to the lo ...

Using a JavaScript function, transmit information through an Express response

I am working on sending an application/javascript response from my Express server, utilizing data retrieved from MongoDB. This response is intended for loading content on a third party website. All components of the process have been developed, and now I ...

Uploading files using Angular can result in a null HttpPostedFileBase

When working with Angular in conjunction with MVC, I am facing an issue where the HttpPostedFileBase is coming up as null when attempting to upload a file. This is how the HTML looks: <input type="file" data-ng-model="fileName" onchange="angular.eleme ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

Numpy Array Argument Parsing made simple

Is it possible to include an argument in ArgumentParser for an np.array instead of a list? I understand that I can achieve this by: import argparse parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('-foo', action=' ...

Guide on how to use a JavaScript AJAX call to download a text file in Java

I am looking to implement a way to download a text file (e.g. 'something.txt') using an AJAX call rather than just an anchor tag in HTML. Here is the HTML code: <body> <a href="#" id="exportViewRule">Export</a> </body&g ...

PHP reCAPTCHA integration with AJAX functionality

I have been attempting to integrate a reCAPTCHA into my PHP contact form using AJAX. The goal is to present the user with the reCAPTCHA challenge and allow them to input it. If the input is incorrect, an error message should be displayed without refreshing ...

Can the SVG def element be modified?

In my SVG file, there is a defs element structured as follows: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 250 330" onclick="tweenGloss()"> <defs> <linearGradient id="grad" x1="174.6 ...

Prevent duplicate items in an array by utilizing the Map object to add elements

Looking for a way to update an array by adding new values while avoiding duplicates. I've implemented the usage of a Map object to keep track of existing values and tried filtering the new array accordingly. const [items, setItems] = useState([]); ...

I often find myself pondering the significance of objects such as [, thisArg]

At times, I delve into JavaScript code on MDN and come across some confusing syntax like [, thisArg]... for instance, arr.map(callback(currentValue[, index[, array]])[, thisArg]) In this scenario, I am aware that a callback function is required. But what ...

Tips for customizing the border radius style of the menu in Vuetify's v-autocomplete component

I am looking to customize the appearance of the drop-down list in the v-autocomplete component by adding a border-radius style, as depicted in the image below. The current design I have achieved closely resembles the visual shown below. Previously, I app ...

What are the steps to enable a Vue component to handle its own transitions?

I am looking for a way to handle enter and leave animations in Vue when components are mounted or removed. My goal is to consolidate all the animation code into its own component for better organization. <template> <transition @enter="enter" ...

Dynamic CSS Changes in AngularJS Animations

I am currently working on a multi-stage web form using AngularJS. You can see an example of this form in action by visiting the link below: http://codepen.io/kwakwak/full/kvEig When clicking the "Next" button, the form slides to the right smoothly. Howev ...

How can JavaScript pass a variable through the URL?

I am attempting to pass a variable through the URL: http://localhost/new_wiki/test.php?id=http://example.com In my code, I have var first = getUrlVars()["id"];. This line is supposed to pass the value but it doesn't seem to be working. Can someone pl ...

Pagination in DynamoDB: Moving forward and backward through your data

Currently, I am utilizing DynamoDB in combination with NodeJS to display a list of objects on the user interface. Given that DynamoDB can only process 1MB of data at a time, I have opted to implement pagination. This allows users to navigate between pages ...

Trigger a jQuery event when a different selection is made in the dropdown menu

There are 2 choices available in the dropdown menu. <select id="_fid_140" onchange="chooseRecordPicker()" > <option value="736">9000000146</option> <option value="x3recpcker#">&lt; Browse choices... &gt;</option> Upo ...

Can jQuery effortlessly glide downward, come to a stop, continue downward, and then move upwards?

My webpage features a large table created and populated automatically every minute using ajax. The code structure is as follows: $(document).ready(function(){ setInterval(function(){ $.ajax({ //code to call backend, get the data, ...

TypeScript combined with Vue 3: Uncaught ReferenceError - variable has not been declared

At the start of my <script>, I define a variable with type any. Later on, within the same script, I reference this variable in one of my methods. Strangely, although my IDE does not raise any complaints, a runtime error occurs in my console: Referenc ...

Why isn't the externally loaded JS file executing properly?

My javascript code functions properly when it's embedded within the HTML file. However, I encounter issues when I try to import it externally. The Google Developer Tools indicate that the file has been loaded successfully, but there seems to be no vis ...