What is the method for exclusively retrieving the matched/filtered string from an array?

I am currently developing a small application that connects to an API to display Magic: The Gathering cards on an HTML webpage. These cards should be searchable, but as I am still learning and in school for this subject, I need help creating a filter function.

So far, I have extracted the card names into a variable called "arr" and am attempting to filter or match them with a value from the search input field labeled "strInput".

document.getElementById("searchButton").addEventListener("click", function(e){
    
    const parentDiv = document.getElementById("cards");
    if (parentDiv.hasChildNodes() === true) {
        removeStuff();
    } else {
        filteredCards("https://api.magicthegathering.io/v1/cards");
    }

}, false)

displayCards("https://api.magicthegathering.io/v1/cards");

function filteredCards(url) {
    fetch(url)
    .then((resp) => resp.json())
    .then((data) => { 

        let myInput = document.getElementById("search").value;
        let strInput = '"' + myInput + '"';
        let arr = [];

        for (i in data.cards) {
            let jsonValue = data.cards[i];
            let name = jsonValue.name;
            arr.push(name);   
        }
         
        let result = strInput.match(arr);
        console.log(result);
        console.log(arr);
        console.log(strInput);
    });
};

console.log(arr); // returns NULL even though the string matches.

Answer №1

There are two straightforward ways to accomplish this task that come to mind: .find() and .filter()

.find() will retrieve the first matching item as a string

.filter() will return all matches in an array format

Both methods utilize a similar coding style, with the main difference being the method name used

arr.filter(item => item === strInput)
|
arr.find(item => item === strInput


As a side note, you can replace several lines of code to enhance efficiency

let arr = [];

for (i in data.cards) {
  let jsonValue = data.cards[i];
  let name = jsonValue.name;
  arr.push(name);   
}

This can be simplified by using the map function

let arr = data.cards.map((card) => card.name);

.

Additionally, there's no need to use '"' + myInput + '"' to convert something to a string. Instead, you can simply employ myInput.toString(). Although if your data specifically requires quotes around certain values, make sure to take that into account.

Answer №2

When passing a parameter to the match method, it's important to note that it should be a regular expression, not just a string. The method requires a valid regex.

To achieve this, create a simple regex expression and loop through the data.cards array, adding elements that meet the condition. Utilize the filter method available for arrays.

let myInput = document.getElementById("search").value;
let myInputRegex = new Regex(myInput, 'gi');
let arr = [];

const matchedTokens = data.cards.filter(card => {
  return card.name.match(myInputRegex);
});

console.log(matchedTokens);
console.log(strInput);

Answer №3

Creating a method that utilizes array.Find() is a great way to search for a specific element in an array. Simply pass in the array and the target string input, and array.Find() will locate the first matching element.

findElement: function (arr, strInput) {
  var element = arr.find(item => item === strInput)
  return element
}

If you'd like to dive deeper into this topic, check out the official Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Answer №4

Thank you for your help! I found exactly what I needed :)

const userInput = document.getElementById("search").value;
const inputRegex = new Regex(userInput, 'gi');
const array = [];

const matchedItems = data.cards.filter(item => {
  return item.name.match(inputRegex);
});

console.log(matchedItems);
console.log(strInput);

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

Subtracting time in ReactJS with Moment.js for efficient date and time operations

I'm currently utilizing React Js and looking to subtract time in JavaScript using the moment library. Below is my attempted code: timecheck(){ var time1 = moment().format("09:00:00"); var time2 = moment().format("00:03:15" ...

The function "getWatchLength" is being called in the render process without being defined on the instance. Remember to define reactive data properties in the data option of Vue.js

I have a Vuex store that holds the state of the number of watched products. I am able to retrieve the product length from my store, but every time I attempt to {{getWatchlength}} in my code, I receive an error stating that "getWatchlength" is not defined ...

NodeJS is throwing a `ReferenceError` because the `io` variable is not

I am working on a NodeJS project and I need to access a variable that is defined in my app.js file from another file. Is this possible? Here is my code: app.js var app = express(); var io = require('socket.io').listen(app); ... otherFile ...

"when using .each to parse JSON, the result comes

Hello! I am facing an issue with the code snippet provided below: $.ajax({'type':'POST', 'url':'https://www.123.com/site/gethistory', 'data':{'a': this.username, 'b': username}, ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

What is the method for obtaining receipt numbers in sequential order, such as the format AB0810001?

Is AB the receipt code that should remain constant followed by the current date (08) and 10001 as the receipt number? ...

Exploring Arrays in C++: Searching and Summarizing

REVISED SECTION: Here are the modifications I have implemented in my code: ifstream infile; infile.open("sales.txt"); if ( !infile.is_open() ) cerr << "file didn't open" << endl; if (!infile) { cout << "Forget something?" ...

modify the name attribute of a select dropdown using jQuery dynamically

In my current project, I am working on dynamically changing the "name" attribute for each select box based on user interactions. The scenario is as follows: When a user clicks on an option in the first select box, a new select box appears with the remainin ...

Rendering EJS Template Views Dynamically Based on Conditions within the Same Path

Hey there, I have a question as a complete beginner. I've been searching for hours and can't seem to find a solution for my specific issue (I'm sure it's something simple). I am working with data from an sqlite database table, filterin ...

The Drop Down Menu feature in Bootstrap is malfunctioning within the context of a NextJS project

I've built a NEXT.JS application using VS Code. The issue I'm facing is with the drop down menu in the navigation bar - it's not sliding down to display the menu when clicked. Here is the code I'm working with: const loggedRouter = () ...

Reverse a filter within an ng-repeat loop - AngularJS

I have a question that I haven't found the answer to yet. Here is the issue I'm facing: The JSON data I am working with has this structure: [{ "batch_queue_name": "Batch One", "start_date": "12/01/2016 10:18 P.M.", "end_date": "12/03/2016 ...

issue with manipulating URLs in Express routing

Looking for assistance with Express routing. I want users to only see localhost:3000/page2 when they go to /page2, instead of localhost:3000/page2.html I have three HTML pages - page1.html, page2.html, and page3.html. I've created a server using Expr ...

Ways to adjust the color of a cell in a table

I am working on customizing a table in my website where I need to change the color of a single cell in each row, similar to the example shown in this image: https://i.sstatic.net/1wtit.jpg Here is the HTML code that I have implemented so far: < ...

Perform an ajax POST call to a server using ajax/jQuery techniques

I am attempting to utilize ajax to send a post request to a different domain and receive a json response. The server is located within my company premises and the logs show that it is indeed sending back a json response. Below are two samples of my attemp ...

When you click on the Prev/Next arrow in the JS slider, the image suddenly

I've been struggling to find a solution for this issue. This is my first attempt at using JS as I am in the process of learning. It's very likely that I'm not fully grasping the answers from my searches - apologies for that. What I'm l ...

Adjusting the parent div width to match the child div width

Here is the code I am working with: <div class="head_title"> <img src="/path/to/image.png"> <h1 id="entryTitle"> <!--Cufon Font--> </h1> </div> I am trying to make the img element stretch to the full width of ...

Obtaining the total count by using getGridParam() following the execution of trigger("reloadGrid")

I am trying to retrieve the total count of records after conducting a search. However, I am encountering an issue where getGridParam("records") does not return the correct value after trigger("reloadGrid"). Below is the code that I am using: goSearch : f ...

Getting rid of the white corners on points using ThreeJS

MY CURRENT PROJECT My current project involves rendering circular points with varying vertex colors using a fragment shader. I am aiming for the points to behave like more performance-efficient spheres, especially when zoomed in for anti-aliasing. ISSUE ...

Add a dynamic widget to a specific element in the document object model in real time

Is there a way to dynamically create a jQuery UI widget using a string? You can easily do this by following the example below: $(function() { $("selector").widget() }) However, what I am trying to accomplish is slightly different. Here is an examp ...

Employing the new operator in conjunction with a variable

Is there a way to achieve the following scenario: var foo = function(){ this.value = 1; } var bar = "foo"; var baz = new bar(); alert(baz.value) // 1 Specifically, I am looking for a method to instantiate an object using its string name. Any sugge ...