JavaScript code to locate the most pertinent strings within an array based on a specific substring

I'm working with a large array containing names of people, such as:

let names = [
   "John Brown", 
   "Tristan Black", 
   "Carl Jobbs", 
   "Aidan Burrows", 
   "Taylor Joe"
];

When given an input, I want to return the top 5 most relevant results from this array. Currently, I am using a loop to check for names like this:

if(name.toLowerCase().includes(input.toLowerCase()))
{
    console.log("Found match : " + name);
}

However, this method is not effective in finding the most relevant search results as it matches any name with the input in it.

My ideal solution would be to iterate through the array of names and identify the top 5 results that are most similar to the input. How can I achieve this?

Answer №1

Based on my understanding of your query, the following function should meet your requirements:

function searchByName(input, nameList) {
  
  return nameList.filter(name => (name.toLowerCase().includes(input.toLowerCase())))
}

let names = ["Sarah Smith", "Michael Johnson", "Emily White", "Adam Brown", "Olivia Green"];

console.log('Matches for Emm:', searchByName('Emm', names))
console.log('Matches for John:', searchByName('John', names))
console.log('Matches for Mic:', searchByName('Mic', names))

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

I am encountering an issue with a JS addition operator while working with node.js and fs library

I'm trying to modify my code so that when it adds 1 to certain numbers, the result is always double the original number. For example, adding 1 to 1 should give me 11, not 2. fs.readFile(`${dir}/warns/${mentioned.id}.txt`, 'utf8', ...

How to Assign a Specific ID to the Body Tag in Wordpress Using functions.php

Struggling to find a simple solution after scouring the web for answers. Most tutorials are overly complicated. I'm attempting to integrate a jQuery menu system into my Wordpress site and want to assign a unique body ID to make targeting easier. I p ...

Guidance on uploading a file with AJAX in PHP following the display of a Sweet Alert

I am currently facing an issue with inserting a file input (images) into my database. When I try to insert it, the value returned is empty. Below is the script I am using: <script> $("#insertform").on('submit',(function(e) { ...

Utilizing window.matchMedia in Javascript to retain user selections during page transitions

I am encountering difficulties with the prefers-color-scheme feature and the logic I am attempting to implement. Specifically, I have a toggle on my website that allows users to override their preferred color scheme (black or light mode). However, I am fac ...

Using VBA and Selenium to access iframes within HTML with the #document tag

I am currently facing a challenge in accessing the HTML content within two iframes using Selenium Basic in VBA. Due to restrictions on our machines, we are unable to use IE and other tools like Python are not available to us. In the past, I was able to ac ...

How does the designated callback function in the filter method effectively remove any missing values from the array?

//Snippet of JavaScript code let sparseArray = [5, , 3, , 1]; let denseArray = sparseArray.filter(() => true); console.log(denseArray); The filter function in the callback removes empty elements from the sparse array. Output: [5, 3, 1] Explanation: ...

Developing a search feature within a MEAN stack application

I'm a beginner in the world of MEAN stack applications and I'm curious about how to incorporate search functionality into my application. While I've done some research on the topic, most suggestions point towards using elastic search. Do you ...

The use of an Authorization header is not compatible with HTTP GET requests

I recently incorporated VueSession into my project to handle user sessions. One of the components in my application is a login form that communicates with my backend (Django) to obtain a JWT token. However, I encountered an issue where although the login p ...

Tips for using a .map() function in conjunction with a promise

I am faced with a challenge where I have an array and for each element in the array, I need to retrieve some data based on that element and then append it to the respective element in the array. For illustration purposes, I will create a simulated fetch o ...

Having trouble generating a dynamic ref in Vue.js

I am currently working on rendering a list with a sublist nested within it. My goal is to establish a reference to the inner list using a naming convention such as list-{id}. However, I'm encountering difficulties in achieving this desired outcome. B ...

Locate a specific class inside a div and switch the CSS style to hide one element and reveal another

I have two divs, each containing a span. By default, the display of each span class is set to none. My goal is to toggle the display property of the span within the clicked div. If the span is already visible, I want to hide it; if it's hidden, I want ...

When using jQuery, the script will execute successfully only when running it chunk by chunk in the console, rather than running the

As I tidy up an html page, my main task is to remove anchor tags and keep the text nodes. To achieve this, I am enclosing all text nodes (without any surrounding elements) within the <asdf> tag. Additionally, I am deleting empty elements such as < ...

Hey there, I'm looking to automatically delete new users from my mongoDB atlas database if they haven't verified their phone number within 2 minutes. I believe using the TTL feature would be

Database Schema In my User schema, the field isVerified is initially saved as false. The user enters their phone number, receives a verification token via SMS, and both the token and number are saved in the database. Once the user enters the verification ...

Having trouble with your YouTube Live Stream not playing in the React Player version 2.9.0?

I successfully integrated react-player into my react.js website and it was working perfectly. However, after a few days, it suddenly stopped functioning. Even updating the plugin to version 2.9.0 did not resolve the issue. Strangely enough, standard YouTub ...

Why isn't Google Map showing up in my HTML <div> section?

I am currently working on a web page that consists of two containers. The mainmapdiv container covers the entire page, while the mainhomediv container is positioned on top of the mainmapdiv. My goal is to hide the mainhomediv container and show a Google Ma ...

Using a variable to store the value of the id attribute in HTML code

How can I dynamically add an ID attribute to an HTML element using a variable declared in JavaScript? Using jQuery var table_row = $('table').find('tr#' + pid); var name = table_row.find('td:nth-child(1)').html(); table_ ...

What is the best way to verify changing input fields in vue.js?

Validation of input fields using vuelidate is essential. The input field in question is dynamic, as the value is populated dynamically with jsonData through the use of v-model. The objective: Upon blur, the goal is to display an error if there is one; ho ...

Generate a loop specifically designed to execute the code following the menu in the script

My website has the code snippet below: let txt_com = document.querySelector(".text_user"); let num_com_user = document.querySelector(".massage_for_user"); txt_com.addEventListener("click", function() { if (this.classList.contains("num_com_user")) { ...

An assortment of the most similar values from a pair of arrays

I am seeking an algorithm optimization for solving a specific problem that may be challenging to explain. My focus is not on speed or performance, but rather on simplicity and readability of the code. I wonder if someone has a more elegant solution than mi ...

Initiate the process of displaying data on a datetime chart using Highcharts

I am currently developing a yearly chart, but I've encountered a small issue. The chart begins in January, however there is no data available until May. The client specifically wants the chart to only display when there is data available, and unfortu ...