Is it possible to combine multiple filter examples together?

Could you please provide some examples or references related to the next task:

var planets = [{
        residents: [{
                name: 'Mars'
            },
            {
                name: 'Jupiter'
            },
            {
                name: 'Saturn'
            }
        ]
    },
    {
        residents: [{
                name: 'Mars'
            },
            {
                name: 'Saturn'
            }
        ]
    }
]

In

<input type='text'>

If I type "Mars and Jupiter" - I expect to get planets[0] object

If I type "Mars and not Jupiter" - I aim to retrieve planets[1] object

The QUERY is how do you analyze the text and determine where the keywords AND and NOT are located? I hope my explanation was sufficient. Thank you in advance and have a wonderful day!

Answer №1

Presented here is a custom function designed to extract names and exclude certain terms from an array. Users have the ability to customize their own filtering criteria.

function findNamesAndExclusions(text) {
    var names = [],
        exclusions = [];
    text = text.replace(/\s\s+/g, ' '); // eliminate extra spaces
    var words = text.split(' ');
    for (var i = 0; i < words.length; i++) {
        var word = words[i].toLowerCase();
        if (i == 0)
            names.push(words[i]);
        else if (word != 'and' && word != 'not') {
            if (words[i - 1].toLowerCase() != 'not')
                names.push(words[i]);
            else
                exclusions.push(words[i]);
        }
    }
}

Answer №2

When it comes to parsing text and executing code based on it, things can get complex. The key is to simplify the rules of the system as much as possible.

One challenge that arises is distinguishing a name from common keywords like and or not. One approach could be maintaining a list such as const keywords = ['and', 'not'] and treating anything outside this list as a name. But what about case sensitivity? Should we consider capitalization, for example, treat And as a name because it's capitalized? Capitalization might serve as a simple way to differentiate names from non-names.

These are just a few aspects to consider among many others.

For the sake of simplicity, let's assume the problem at hand is straightforward. We only aim to achieve the minimum goal. For instance, assuming all names should be included except those preceded by the keyword not.

// This implementation is overly simplistic and unsuitable for production. It may fail with basic issues like whitespace.
const isName = (str) => {
    return str[0] === str[0].toUpperCase();
};

const input = document.querySelector('input[type="text"]');
input.addEventListener('change', (evt) => {
    const tokens = evt.target.value.split(' ');
    const names = tokens.filter((name, i, arr) => {
        return isName(name) && arr[i - 1] !== 'not';
    });
    const company = {
        members : names.map((name) => {
            return { name };
        })
    };
});

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

The dataTable plugin is malfunctioning, displaying all records on a single page when it should only show 10 per page

I utilized the dataTable plugin to format my HTML table, but unfortunately it is not displaying the results as expected. Instead of showing 10 records per page, it is displaying all records at once. I even tried setting "iDisplayLength: 10" but it didn&apo ...

The specified property cannot be found within the type 'JSX.IntrinsicElements'. TS2339

Out of the blue, my TypeScript is throwing an error every time I attempt to use header tags in my TSX files. The error message reads: Property 'h1' does not exist on type 'JSX.IntrinsicElements'. TS2339 It seems to accept all other ta ...

Verify if spacebar is pressed and then use jQuery to add a hashtag with multi-language support

I am attempting to use jQuery to add a hashtag (#) after the user types and presses space. I have created a demonstration on CodePen. In this demo, when you type something like (how are you), the JavaScript code will change it to (#how #are #you). To ach ...

Tips for dividing by a large number

I am currently attempting the following: const numerator = 268435456; const denominator = 2 ** 64; const decimalFraction = numerator / denominator; In order to achieve this, I have experimented with utilizing the code provided in this link: : const rawVal ...

The object in question cannot be used as a constructor

I'm currently facing an issue while attempting to define and initialize an object in JavaScript. Despite my code appearing correct, I am unable to comprehend the underlying problem. Here is the snippet of my code: class Account { construct ...

Angular JS: the output of the initial resolution will not be transferred to the subsequent resolution

I can't wrap my head around why I keep getting an Unknown Provider error with the code below "geonameProvider <- geoname <- country" var cacRouteViewMod = angular.module('cacRouteViewMod', ['ngRoute', 'cacLib'] ...

Can anyone help me find the Ajax URL for October CMS?

I'm interested in implementing Angular JS with October CMS. Can someone guide me on how to send data to the controllers via a POST request? Upon digging through the October framework.js file, I came across this code snippet: headers: { 'X-O ...

Preventing redirection post-AJAX call using jQuery

Currently, I am attempting to implement a basic form submission using AJAX to send data to submit.php for database storage. However, upon submission, the page redirects to submit.php instead of staying on the current page. How can I make it submit without ...

Extract items from javascript array based on their index value

Recently I came across a javascript array var countries = ["India","USA","China","Canada","China"]; My goal is to eliminate "China" only from the 2nd position while keeping the rest intact. var countries = ["India","USA","Canada","China"]; I am see ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Arrange the Elements of Select Options

I am currently facing an issue with organizing the elements in my select list. I have two interconnected lists, one containing a list of "models" which I have successfully sorted using the following function: var sel = $('#model'); var opts_lis ...

What is the process for retrieving data from a javascript file that was submitted through a form?

Can you help me with an issue I'm having with this code snippet? <form action="main.js"> <input type="text" required="required" pattern="[a-zA-Z]+" /> <input type="submit" value="Submit" /> </form> After c ...

Is window.getComputedStyle not functioning as anticipated?

Here is a function I created to determine the width and height of a text: function size_calculation(word,fontSize) { const div = document.body.appendChild(document.createElement('div')); div.textContent = word; div.style.cssText = ` fo ...

What could be causing the issue with my code where the canvas is not showing boxes beyond a y-coordinate of 8 along the x-axis?

I've been working on creating a 64 square checkerboard using the html canvas element in javascript, but I'm encountering an issue. The boxes aren't rendering properly after the first 8 squares on the y-axis, and I can't figure out where ...

Guide to dynamically load external JavaScript script in Angular 2 during runtime

Currently, I am integrating Twitter digits for authentication purposes. To implement this feature, a small .js script needs to be downloaded and initialized. The recommended approach is to directly fetch the file from the Twitter server. In order to succe ...

The method window.scrollTo() may encounter issues when used with overflow and a height set to 100vh

Suppose I have an HTML structure like this and I need to create a button for scrolling using scrollTo. However, I've come across the information that scrollTo doesn't work well with height: 100vh and overflow: auto. What would be the best way to ...

I'm having trouble getting the HTML checkbox symbol to show up correctly. My goal is to create all the elements using the DOM

I am currently building all of my elements manually through the DOM tree, and I am attempting to insert a checkbox symbol in this manner: //Add date var tdDate = document.createElement("td"); tdDate.textContent = ("" + workoutList[idx].date); ...

Reinitializing AngularJS form controls

Check out this codepen example: http://codepen.io/anon/pen/EjKqbW I'm trying to reset the form elements when the user clicks on "Reset". The div elements f1,f2,f3 should be hidden and the searchText box cleared. However, the reset button is not trig ...

AngularJs gm.datepickerMultiSelect is experiencing an issue with dates

I am currently working on implementing the gm.datepickerMultiSelect module in AngularJS. I have encountered an issue with a day offset when selecting a date and have pinpointed the line in the library that is causing the problem: var dateVal = Date.parse( ...