Look up a string array using a specified user and provide the indexes of the matching string array elements

I am facing an issue with finding the indexes of phrases that contain a specific keyword in an array.

var possibleValues=["contacts","delete","new contact","add","display"];

The user input can vary, it could be "contacts" or even "how to create a contact?". My function needs to return the indexes of phrases in the array that include the keyword 'contact'. I have attempted a logic but haven't been successful so far. Here is what I have done:

var indexes = [];
for (i = 0; i < possibleValues.length; i++) {
  if (arr[i].indexOf(userinput) != -1 || userinput.indexOf(arr[i])!=-1) {
    indexes.push(i);
  }
}

If anyone has some insights on how to solve this issue, your help would be greatly appreciated!

Answer №1

Your solution is very close to being correct. The key adjustments needed are comparing with -1 instead of 1, and using possibleValues[i] instead of arr[i].

If you aim to match each word in the user input, you must separate it into individual words and introduce an additional nested loop.

var possibleValues = ["contacts", "delete", "new contact", "add", "display"];
var userInput = "how to create contact";
var words = userInput.split(' ');
var indexes = [];
for (let i = 0; i < possibleValues.length; i++) {
    for (let j = 0; j < words.length; j++) {
        if (possibleValues[i].indexOf(words[j]) != -1 || words[j].indexOf(possibleValues[i]) != -1) {
            indexes.push(i);
            break;
        }
    }
}
console.log(indexes);

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

Emberjs promises are enhanced with a filtering feature

My goal is to develop a search functionality using a JSON API. After following tutorials and successfully implementing it with provided examples: export default Ember.ArrayController.extend({ searchText: null, searchResults: function(){ ...

Tips for relocating a CSS button

I have designed two buttons using css and I am looking to align them below the title "forecast customer activity". Due to extensive styling in css, the code might appear lengthy. Requesting assistance with a solution after reviewing the following code snip ...

Creating Object of Objects in TypeScript: A Comprehensive Guide

Assuming I have a structure similar to this: interface Student { firstName: string; lastName: string; year: number; id: number; } If I intend to handle an array of these structures, I can simply specify the type as Student[]. Instead of utilizin ...

How can URL parameters be connected to context in a React portfolio website?

I have a compact portfolio site created with React that showcases my work as both a graphic designer and an aspiring web developer. Upon arrival, visitors encounter a landing page where they can choose to explore either the "design" or "web" sections, sett ...

Adding text chips to a text field in Vuetify - A simple guide

I have successfully integrated a text field with vuetify and now I am looking to incorporate chips into it. Currently, chips are only added if the entered text matches a specific pattern (such as starting with '{' and ending with '}'). ...

Perform bulk updates to various rows and columns based on their individual IDs within a Microsoft SQL Server

After extracting data from the database in Excel format using an SQL join query, I made modifications to some columns in the Excel sheet. Now, I need to update the modified data back into the database using the respective row IDs. However, when I try to it ...

Angular = encountering an incorrect array size limitation

I am encountering an issue with the function in my controller... $scope.pagerPages = function (n) { var i = Math.ceil(n); return new Array(i); } The n value is derived from an expression on the view and can sometimes be a fraction. This is why I ...

Maximizing efficiency in processing multiple requests simultaneously using ajaxSetup's data

I need to enhance an existing ajax request within our CMS by adding additional data. Specifically, I am working with a media library that loads image data (json), and I want to incorporate more images from an external source. var promise_waiting = []; jQu ...

Perform a series of sequential HTTP requests using the got.js library and Promise objects

Looking to use the got library for making http requests while correctly implementing Promises. Despite my efforts to use Promises in my code, they never seem to work as expected. Take a look at this pseudo-code snippet: function obtainToken() { var ...

Loop through the component name and route path in ReactJs to efficiently organize and structure your application

In my route file coding for ASP.NET, I am creating routes by fetching details from the backend. Successfully getting details like [Contacts, Pipelines, Stages]. import * as React from 'react'; import { BrowserRouter, Redirect, Route } from &apos ...

The minimum and maximum limits of the Ionic datepicker do not function properly when selecting the month and day

Recently, I have been experimenting with the Ionic 2 datepicker. While the datepicker itself works perfectly fine, I've run into some issues when trying to set the min and max properties. <ion-datetime displayFormat="DD-MM-YYYY" [min]="event.date ...

Continuously update in JavaScript based on a condition, cease updating when the condition no longer

I have a scenario on my page where specific data needs to be refreshed every minute, but at the same time, the user should be able to view and edit certain modals. I want to ensure that when a modal is open, the data refreshes are paused so that the modal ...

React's useState feature is doubling the increment

I have created a basic form management system with a historical feature. A simplified version of this system can be seen on codesandbox import { useState } from "react"; import "./styles.css"; const sample = ["what", "w ...

What is the best way to make sure that only one tab changes color when clicked?

I have been working on a function that changes the color of a tab to gold when clicked, which is working fine. However, I also want to toggle the active property of each tab so that it displays a nice white outline. The problem I'm facing is that the ...

Styling the active selection in nav class with bold attribute in Bootstrap/AngularJs

How can I apply the bold attribute to the currently selected nav bar item? <ul class="nav"> <li role="presentation" ng-repeate="item in items" ng-class="{'active':navLink == item.header}"> </li> &l ...

What is the best way to trigger two functions simultaneously using an onClick event in NextJS?

I have defined two constants in my NextJs app, "toggleMenu" and "changeLanguage". When the language changer inside the menu is clicked, I want it to trigger both of these functions. However, I tried implementing this code but it doesn't seem to work ...

Ways to assign scores to every response button

Below is an excerpt of code that showcases a list of potential answers for each question in the form of checkbox buttons. The task at hand is to assign marks to each answer button, which can be retrieved from the database. Marks for correct answers are obt ...

when input event occurs automatically upon returning to the page

<input type='text' class='binp'> $('.binp').on('input', function(){ alert('lorem'); }); After entering text into the .binp input field and navigating to another page, returning using the browser ...

Utilize jQuery to assign title attributes stored in one array to elements stored in another

In my project, I have twelve <span> elements with the class "has_title" and each one has a unique title. Also, there are twelve <div> elements with the class "bar". The task at hand is to assign the titles from the <span> elements in th ...

What could be causing my JQuery code to fail after loading data via ajax?

My tree view is set up using the following jQuery code: $(".treeView").on("click", ".CollOpen, .CollClosed", function () { $(this).toggleClass("CollOpen CollClosed").nextAll('ul').first().toggle(); }); Initially, this code works perfectly. ...