A guide for finding a specific string within a subset of an array

I have an array containing various substrings, and I want to pass if at least one of those substrings contains the specific value I am searching for.

Value1 = [
  "Grape | 100 |Food Catering Service",
  "Apple | 100,000m |Food Catering Service",
  "Water Melon | 100,000m |Catering Service Outside",
  "100,000m |Food Catering Service Outside
]

Using TypeScript, my goal is to ensure that if any substring in the array contains the word "Food," it should pass. Even if some substrings do not contain the word "Food," the overall test should still pass.

The code snippet below is what I have tried so far, but it does not achieve the desired outcome, as it simply returns the array without filtering based on the search criteria.

export function arraySubstring(expected: string, ignoreCase?: boolean): Expectation<string[], string> {
  return Expectation.that("test", expected, async(actor: Actor, actual: string[]): Promise<boolean> ==> {

    try {
      for (const value of actual) {
        if(ignoreCase) {
          if (!value.toLowerCase().includes(expected.toLowerCase())) return false;
        } else {
          if (!value.includes(expected)) return false;
        }
      }
      return true;
    })
}

const value2 = await webActor.attemptsTo(Ensure.that("my expectation",
  value1, arraySubstring("Food")))

Answer №1

Your code logic hinges on the order of elements. If the first element in the loop doesn't have the term "food", it will return false as return statements immediately exit the function.

A better approach would be to concatenate all entries into a single string and then check the index of the first occurrence using indexOf("food").

const array = [
  "Grape | 100 |Food Catering Service",
  "Apple | 100,000m |Food Catering Service",
  "Water Melon | 100,000m |Catering Service Outside",
  "100,000m |Food Catering Service Outside",
];

const found = array
  .reduce((obj, entry) => obj.concat(entry))
  .toLocaleLowerCase()
  .indexOf("food");
if (found >= 0) {
  console.log("Array contains food");
} else {
  console.log("Array does not contain food");
}

If you wish to iterate through the array, consider returning on the true case to eliminate the dependency on element order in your code.

const array = [
  "Grape | 100 |Food Catering Service",
  "Apple | 100,000m |Food Catering Service",
  "Water Melon | 100,000m |Catering Service Outside",
  "100,000m |Food Catering Service Outside",
];

const ignoreCase = true;
const expected = "Food";

const containsExptected = (_array) => {
  for (const value of _array) {
    if (ignoreCase) {
      if (value.toLowerCase().indexOf(expected.toLowerCase()) >= 0) return true
    } else {
      if (value.indexOf(expected) >= 0) return true;
    }
  }
  return false;
};

const found = containsExptected(array);
if (found) {
  console.log("Array contains food");
} else {
  console.log("Array does not contain food");
}

Answer №2

Here's a quick way to search for a partial match in an array of strings:

const items = ["Banana | 50 | Fruit Stand", "Orange | 75 | Grocery Store", "Apple | 100 | Farmers Market"]
const searchTerm = "Fruit"
const caseInsensitive = true
console.log(items.some(item => (caseInsensitive ? item.toLowerCase().includes(searchTerm.toLowerCase()) : item.includes(searchTerm))))

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

jaydata integration with sorting capabilities

Utilizing JayData, I am fetching a table along with other tables through a join operation. The code I have written is as follows: db.Table1.include("Table2").include("Table3").toArray(); However, my issue arises when I try to sort the data based on a fi ...

Transferring information to a view using ExpressJS and Reactjs

I have created an application that requires users to log in with Twitter credentials. Once logged in successfully, I typically pass the user data to the template using the following code: app.get('/', function(req, res, next) { log("The ...

The 'DOCUMENT' module (imported as 'i23') could not be located within '@angular/platform-browser'

During my upgrade from Angular version 7 to 8, I encountered an error when building the project even though I am not using DOCUMENT. It seems like something is causing this issue that I am overlooking. I have thoroughly checked all the files and confirmed ...

Error: Invalid argument type

I'm encountering difficulties retrieving data from an API as I delve into learning Angular 2. The error message I am facing is: url.js:106 throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'url', 'string', url); Typ ...

A node module designed to efficiently convert multiple TIFF images into a single multipage TIFF document

Looking to combine several tiff images into a single file using nodejs/javascript. Is there a method to create a single tiff file with multiple pages from separate tiff images in nodejs? Can we convert a multi-page pdf into one tiff image using nodejs? ...

Creating a Validation Form using either PHP or JavaScript

I need to create a form with the following columns: fullname, email, mobile, and address. If the visitor fills out the mobile field, they should only be allowed to enter numbers. And if the visitor fills out the email field, they should only be allowed to ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

Troubleshooting React's failure to start with node.js running behind an Nginx Reverse Proxy

This is my first attempt at setting up a Node.js server in production (other than one Meteor server), and I've run into a problem that I can't figure out on my own. I have built an application using React. Here is the server code: // Imports va ...

A guide on crafting a test scenario for an AngularJS controller using the Jasmine framework

I recently created an angular module called userModule.js 'use strict'; angular.module('users', ['ngRoute','angular-growl','textAngular','ngMaterial','ngMessages','ngImgCrop', ...

Whenever I attempt to include state in a React class that is declared as a constant, I consistently encounter the error message: "TypeError:

Apologies for the redundancy, but as a newcomer to React, I previously inquired about a similar issue and have since modified my code. My current challenge involves trying to access a state value within a const React class. Below is the excerpt from my Ar ...

What is the best choice for managing state storage and retrieval when working with React, React Router, and React Relay?

As I navigate through my app using React, React Router, and React Relay, I encounter different ways of handling data updates. React offers useState, React Router has its pushState wrapper (location.state), and Relay utilizes the updater() method. However, ...

What is the best way to implement a callback in JavaScript (Node) in order to ensure that an asynchronous function finishes before moving on

I have a function called translateCommand(command) that uses a Translate package from npm to translate some text into a different language. The issue arises because the translate function provided by that package is asynchronous, causing the translateComma ...

Backbone - NestedModels - Issues with nested sets not triggering 'change' event

I have incorporated the Backbone nested plugin into my project. The way I set up my binding is as follows : var view = Backbone.View.extend({ initialize: function(params) { this.model.bind('change', _.bind(this.rerender, this)); ...

Guide to making Bootstrap collapsible panels with full-width content that do not affect neighboring columns

I'm currently working on a responsive grid that displays items with expandable details when clicked. My issue is that when one item expands, the elements next to it collapse down, which is not what I want. I want all items to stay at the top and have ...

Converting an array of objects into an array of Objects containing both individual objects and arrays

I am dealing with an object const response = { "message": "story records found successfully", "result": [ { "created_AT": "Thu, 13 Jan 2022 17:37:04 GMT", ...

Unexpected expression after upgrading to TypeScript 3.7.2 was encountered, file expected.ts(1109)

After updating TypeScript from version 3.6.x to 3.7.2, I started using optional chaining in my code. However, I encountered a peculiar error. Error message: Expression expected.ts(1109) This error appeared in both my (vim, VSCode) IDE, even though the ...

Inquiry to an outside domain

I need to send a request to an external domain, ensuring that the parameter is correctly sent to a PHP file on the external server. However, I'm facing an issue where "request.responseText" always returns empty. Any assistance in this matter would be ...

The concept of ExpectedConditions appears to be non-existent within the context of

Just starting out with protractor and currently using version 4.0.2 However, I encountered an error with the protractor keyword when implementing the following code: import { browser } from 'protractor/globals'; let EC = protractor.Expe ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

Tips for checking a form without scrolling down in angularjs?

Trying to create a form validation for the 'Agree to Information' page. The user must scroll down to proceed, without a checkbox at the bottom of the box. If the user clicks continue/agree without scrolling, an error div element should display wi ...