Struggling to sift through words within the strainer

I attempted to use the toLowerCase method for filtering words and domain names, but I keep receiving an empty array. I used the toLowerCase method to ensure that data containing capital letters or searched by capital letters are converted to lowercase. Below is my code:

var data = [ {
"name": "test",
"domain": "domain2",
"subdomain": "subdomain5",
"type": "yes"
},
    {
"name": "test",
"domain": "domain2",
"subdomain": "subdomain6",
"type": "no"
},
    {
"name": "hello",
"domain": "domain2",
"subdomain": "subdomain6",
"type": "no"
},
    {
"name": "hello",
"domain": "domain2",
"subdomain": "subdomain6",
"type": "no",
        "desc":"hello"
},
     {
"name": "hello",
"domain": "domain5",
"subdomain": "subdomain6",
"type": "no",
        "desc":"hello"
}
    
];

var namesearch = ["he"];
var domain = ["domain5","domain2"];
var result = data.filter((d)=>{
return (namesearch.length > 0 ? namesearch[0].toLowerCase().indexOf(d.name.toLowerCase()) > -1:'') &&  domain.length > 0 ? domain.includes(d.domain):''
});
console.log(JSON.stringify(result));

Answer №1

Your current approach to using indexOf is incorrect. Here is the correct way to use it:

d.name.toLowerCase().indexOf(namesearch[0].toLowerCase())

var data = [
  {
    name: "test",
    domain: "domain1",
    subdomain: "subdomain1",
    type: "yes"
  },
  {
    name: "hello",
    domain: "domain2",
    subdomain: "subdomain6",
    type: "no"
  },
  {
    name: "test1",
    domain: "domain2",
    subdomain: "subdomain6",
    type: "no",
    desc: "helloo"
  }
];

var namesearch = ["he"];
var domain = ["domain5", "domain2"];
var result = data.filter(d => {
  return (namesearch.length > 0
    ? d.name.toLowerCase().indexOf(namesearch[0].toLowerCase()) > -1
    : "") && domain.length > 0
    ? domain.includes(d.domain)
    : "";
});

console.log(result)

Answer №2

It appears that there is an excessive use of ternary expressions that do not seem necessary. A more efficient approach would be to test the length of namesearch before applying filtering, as if the length is 0, there is no need to enter the filter block.

 var data = [ {
            "name": "test",
            "domain": "domain2",
            "subdomain": "subdomain5",
            "type": "yes"
        },
        {
            "name": "test",
            "domain": "domain2",
            "subdomain": "subdomain6",
            "type": "no"
        },
        {
            "name": "hello",
            "domain": "domain2",
            "subdomain": "subdomain6",
            "type": "no"
        },
        {
            "name": "hello",
            "domain": "domain2",
            "subdomain": "subdomain6",
            "type": "no",
            "desc":"hello"
        },
         {
            "name": "hello",
            "domain": "domain5",
            "subdomain": "subdomain6",
            "type": "no",
            "desc":"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

Tips for dividing the AJAX response HTML using jQuery

I have a piece of code that is functioning properly. However, I am having trouble splitting the HTML response using AJAX jQuery. I need to split it into #div1 and #div2 by using "|". Could you please provide a complete code example and explanation, as I am ...

Utilize PHP's SplDoublyLinkedList for referencing data

I am attempting to alter the content of an array that is located within a linked list. $z = new SplDoublyLinkedList(); $z->push(array('Hello', 0)); $z->push(array('world', 4)); $p = & $z->offsetGet(1); ...

Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError bl ...

Ways to specify the default value for a component

A sample of my custom component code (Amount.tsx) is shown below: const Price = ({ price, prevPrice }) => { return ( <div className="product-amount"> <div className="price"> {prevPrice ? (<del class ...

Can Google's bot initiate JavaScript click events on a website and how can this be resolved?

Currently, we are facing an issue with the reviews on our website. In order to optimize page load speed on both desktop and mobile, we have decided to initially display only 10 reviews. After each button click by the user, the next set of 10 reviews is loa ...

Upon pressing the browser's back button, the page fails to automatically load with the updated URL

Providing a little context: Let's say I initially access the page using URL1. After that, I use window.history.pushState() to change the URL to URL2. Now, when I click the "back" button, I observe that the address bar displays URL1 again, but the pa ...

Is there a possibility of Typescript expressions `A` existing where the concept of truthiness is not the same as when applying `!!A`?

When working with JavaScript, it is important to note that almost all expressions have a "truthiness" value. This means that if you use an expression in a statement that expects a boolean, it will be evaluated as a boolean equivalent. For example: let a = ...

Utilize user input to fetch data from an external API

Let's say there is a field for 'part number' input that is not enclosed in a form tag. Whenever a user enters a value, the onblur event or a button positioned next to the input field should trigger a query to an external site via its API and ...

Analyzing an exclusive phrase?

I am fairly new to using Python and I have encountered a challenge in parsing a string with a unique format. Within a CSV file, there is a column containing the following pattern: [Chakroff, Alek; Young, Liane] Boston Coll, Chestnut Hill, MA 02167 USA; [R ...

Tips for adjusting the position of nodes that are overlapping in React Flow

Whenever node1 is moved over node2 in react-flow, they end up overlapping. I am looking to shift node2 towards the right to avoid this overlap. The desired outcome is for node2 to be shifted to the right side. ...

The input given to Material UI autocomplete is incorrect, even though the getOptionSelect parameter already exists

I'm currently working on creating my own version of the Google Places autocomplete found in the Material UI documentation. While I have successfully implemented the autocomplete feature and am able to update my component's state with the result, ...

React-virtualized list experiencing performance problems due to react-tether integration within its elements

Description I need help with a challenging issue. I have a long list of items displayed in a react-virtualized VirtualScroll. Each item on the list contains many elements, including one that triggers a context menu. I'm using react-tether to attach t ...

A Typescript Function for Generating Scalable and Unique Identifiers

How can a unique ID be generated to reduce the likelihood of overlap? for(let i = 0; i < <Arbitrary Limit>; i++) generateID(); There are several existing solutions, but they all seem like indirect ways to address this issue. Potential Solu ...

Modify the JS/JQuery variable by utilizing the data entered into an HTML input field

I have implemented a javascript/ajax request on my advanced search page. <script> // window.setInterval(function() // { $(function () { var SearchTerm = '<?php echo $_POST['Search']; ...

Submit numerous queries to verify the presence of a name and assign it to the name attribute

I have a collection of unique devices. As part of a process, I need to assign a default name to each device ("DeviceX" - where X is a sequential number), but some of the names may already be in use. To handle this, I must make a request to check ...

Adding a number repeatedly and showing the result

I have been searching for a solution to this particular problem for quite some time now, but unfortunately, I haven't been able to find one yet. It would be incredibly helpful if someone could guide me in the right direction. Let's say we start ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

Running repetitive tasks in PHP using setInterval function

I've been working on adding a "friend request" feature to my website and I really want the requests to show up instantly without having to reload the page. After doing some research, it seems like using setInterval with Ajax is the way to go. I found ...

Automating the deployment of a vue.js app using GitLab CI/CD pipeline to deploy to

Currently experiencing an issue with the pipelines involving my YAML file that automates deployment of a Vue app to Firebase. Despite including scripts in the file and setting up the Environment variable FIREBASE_TOKEN on GitLab, pushing the code to a GitL ...

Retrieve dynamic data from a website using jQuery's AJAX functionality

I am trying to retrieve the data from example.com/page.html. When I view the content of page.html using Chrome Browser, it looks like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> & ...