Searching for a particular character within an array and removing it as needed

Currently, I am working on developing a feature that will filter out negative responses in a magic 8-ball application. The goal is to exclude any elements from the response array that contain the word "no" while preserving responses that contain words like "now" or "not".

const responses = [
  "It is certain",
  "It is decidedly so",
  "Without a doubt",
  "Yes, definitely",
  "You may rely on it",
  "As I see it, yes",
  "Most likely",
  "Outlook good",
  "Yes",
  "Signs point to yes",
  "Reply hazy try again",
  "Ask again later",
  "Better not tell you now",
  "Can't predict now",
  "Concentrate and ask again",
  "Don't count on it",
  "My reply is no",
  "My sources say no",
  "Outlook not so good",
  "Very doubtful"
]

const negativeResponseDeleter = () => {
    let splitTracker = 0
    let holdingArray = []
    for (i = 0; i < responses.length; i++) {
        holdingArray = responses[i].split(" ")
        if (holdingArray.includes("no")) {
            
        }
                
    } 
}

console.log(negativeResponseDeleter())

The code snippet above represents my current progress on this task, but I am facing some challenges. I am exploring the most effective approach to tackle this issue.

Answer №1

To reverse the condition, store the words in words and check if any of the words in the response do not contain "no". If true, add it to the array and return the final array.

const responses = [
  "It is certain",
  "It is decidedly so",
  "Without a doubt",
  "Yes, definitely",
  "You may rely on it",
  "As I see it, yes",
  "Most likely",
  "Outlook good",
  "Yes",
  "Signs point to yes",
  "Reply hazy try again",
  "Ask again later",
  "Better not tell you now",
  "Can't predict now",
  "Concentrate and ask again",
  "Don't count on it",
  "My reply is no",
  "My sources say no",
  "Outlook not so good",
  "Very doubtful"
]

const negativeResponseDeleter = () => {
    let holdingArray = []
    for (i = 0; i < responses.length; i++) {
        const words = responses[i].split(" ")
        if (!words.includes("no")) {
            holdingArray.push(responses[i])
        }
                
    } 
    return holdingArray
}

console.log(negativeResponseDeleter())

Answer №2

If you want to check if a string contains the word "no" surrounded by boundaries, you can create a regular expression for it. Then utilize the filter method in JavaScript to only return strings that do not match the test.

const responses=["It is certain","It is decidedly so","Without a doubt","Yes, definitely","You may rely on it","As I see it, yes","Most likely","Outlook good","Yes","Signs point to yes","Reply hazy try again","Ask again later","Better not tell you now","Can't predict now","Concentrate and ask again","Don't count on it","My reply is no","My sources say no","Outlook not so good","Very doubtful"];

const re = /\bno\b/;

const output = responses.filter(response => {
  return !re.test(response);
});

console.log(output);

Answer №3

If you want to filter out negative responses from an array, you can use a regex with word boundaries:

const responses = [
  "It is certain",
  "It is decidedly so",
  "Without a doubt",
  "Yes, definitely",
  "You may rely on it",
  "As I see it, yes",
  "Most likely",
  "Outlook good",
  "Yes",
  "Signs point to yes",
  "Reply hazy try again",
  "Ask again later",
  "Better not tell you now",
  "Can't predict now",
  "Concentrate and ask again",
  "Don't count on it",
  "My reply is no",
  "My sources say no",
  "Outlook not so good",
  "Very doubtful"
];

const negativeResponseFilter = () => {
    let filteredArray = responses.filter(str => !/\bno\b/.test(str));
    console.log(filteredArray);
}

negativeResponseFilter();

Filtered Output:

['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', "Can't predict now", 'Concentrate and ask again', "Don't count on it", 'Outlook not so good', 'Very doubtful']

Answer №4

Here is a solution that efficiently filters an array using regex:

const responses = [
  'It is certain',
  'It is decidedly so',
  'Without a doubt',
  'Yes, definitely',
  'You may rely on it',
  'As I see it, yes',
  'Most likely',
  'Outlook good',
  'Yes',
  'Signs point to yes',
  'Reply hazy try again',
  'Ask again later',
  'Better not tell you now',
  "Can't predict now",
  'Concentrate and ask again',
  "Don't count on it",
  'My reply is no',
  'My sources say no',
  'Outlook not so good',
  'Very doubtful',
];

const output = responses.filter(elem => !/(no)\b/g.test(elem));

console.log(output);

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

Optimal method for implementing an arrow function within a React class component while utilizing setState

I'm currently exploring the distinction between two approaches to using an arrow function and updating state in a React class component. Both methods appear to be functional in correctly updating the state. Within a controlled component, the function ...

Leverage the package.json script without relying on any yarn/npm commands

Can scripts commands be executed within the package.json file without needing to include yarn or npm? For example: "scripts": { "get": "node index.js" } Currently, in order to run this script I have to use yarn get [ar ...

Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed General data for display const arr = [ { id: "1", name: "Skoda - Auto" }, { id: "2" ...

Version 5.0.4 of Mui, when used with makeStyles and withStyles, is experiencing issues with applying styles to Mui

I've been diving into a react project using Mui v5.0.4 and encountered an unexpected issue with my custom styles. Initially, everything was functioning smoothly, but suddenly the styles I had defined were no longer appearing as intended in components ...

Executing a loop and retrieving a value using the letter q

I'm looking for the most efficient way to iterate through an array, apply a specific operation to each element, and then return the outcome using Q. Imagine I have the following array: var q = require('q'); var arr = [1, '2', "3" ...

Encountering an error in a basic jest test where the message reads "globalObj.setTimeout is not defined"

Trying to run a simple Axios hook test and encountering the following error: TypeError: globalObj.setTimeout is not a function at setImmediatePolyfill (node_modules/@testing-library/react-native/build/helpers/timers.js:59:20) at Object.then (n ...

Having trouble using Laravel's Eloquent to serialize data to JSON and then sorting the JSON object?

I am facing an issue with sorting a JSON value that I have. Despite my efforts, it is not getting sorted as expected. [ { "id": 15028, "order_id": 342, "user_id": 3, ...

Using express.js to transfer an uploaded image to Amazon S3

Currently, I am faced with an issue of passing an image uploaded from a react application through express to a managed s3 bucket. The s3 bucket is created and managed by the platform/host I am using, which also generates upload and access urls for me. So f ...

Issues with Angular route links not functioning correctly when using an Array of objects

After hard coding some routerLinks into my application and witnessing smooth functionality, I decided to explore a different approach: View: <ul class="list navbar-nav"></ul> Ts.file public links = [ { name: "Home&quo ...

What is the reason for restricting AJAX requests to the same domain?

I'm puzzled by the limitation of AJAX requests to the same domain. Can you explain the reasoning behind this restriction? I don't understand why requesting files from external locations is an issue, especially since servers making XMLHTTP reques ...

Having issues with using useState in a loop with multiple variations in React and NextJs

In my component, I have multiple variants and I want to be able to click on any variant to add an active class while removing the active class from another. However, I'm struggling to figure out how to achieve this using state in a loop that handles m ...

What is the best method for ensuring a user remains logged in even after their access token expires, requiring them to log in again to resume their normal

Currently utilizing the Nuxt-axios module alongside a proxy. Implemented common error handling code in Plugins/axios.js export default function({ $axios, __isRetryRequest, store, app, redirect , payload , next}) { $axios.onRequest(config => { i ...

React and React Router are causing the login screen layout to persistently display

The MUI Theme Provider I have includes a Layout with Dashboard and Order screens. Even though the user hits the '/' endpoint, the Login Screen should be displayed instead of the Layout. -App.js <ThemeProvider theme={theme}> <Router> ...

Ensuring the next tab is not accessible until all fields in the current tab are filled

I am working on a form with a series of questions displayed one at a time, like a slide show. I need help with preventing the user from moving to the next set of questions if there is an empty field in the current set. Below is the script I am using to nav ...

Incorporating PHP in JS/jQuery AJAX for creating unique odd and even conditional layouts

My PHP code includes a loop that changes the layout of elements based on whether the $count variable is odd or even. For odd counts, an image appears on the left and text on the right. For even counts, it's the other way around. To load content dynam ...

Load a specific div using PHP and jQuery upon page load

The other day I came across a jsfiddle example: http://jsfiddle.net/lollero/ZVdRt/ I am interested in implementing this function on my webpage under the following condition: <?php if(isset($_POST['scrolltodiv']){ $goto = "#pliip";} ?> Ba ...

having trouble retrieving information from the input field

I'm having trouble retrieving the user's input from the input field, can someone assist me with this issue? I can't seem to identify what the problem is here. var ftemp = document.getElementById("Farenheit").value; <td> <i ...

What is the best way to remove a particular element from an array stored in Local Storage?

Currently working on a web application that features a grade calculator allowing users to add and delete grades, all saved in local storage. However, encountering an issue where attempting to delete a specific grade ends up removing the most recently add ...

Unexpected jQuery error: Uncaught TypeError - Invocation not allowed

Yesterday, the code was functioning perfectly, but today it suddenly started throwing an error: Uncaught TypeError: Illegal invocation I'm struggling to pinpoint where exactly the issue lies. function createFile() { var selected_retailer_uui ...

Different option to chained promises

In an attempt to develop a function that acquires a presigned s3 URL (call 1) and performs a PUT request to s3, I find myself contemplating the usage of a nested promise structure, which is commonly recognized as an anti-pattern. Outlined in JavaScript/ps ...