Discover all potential matching strings and substrings within an array

Searching for a way to identify matching strings and substrings in an array. For example:

Given a string "3-100" and an array of strings ["3", "3-1", "3-15", "3-",3-10", "3-100"].

When looping through the array, the expected outcomes should be:

"3" -> true,
"3-1" -> false,
"3-15" -> false,
"3-" -> false,
"3-10" -> false,
"3-100" -> true,

What methods can be used achieve this? Previously attempted .includes() which did not work for all cases. Seeking advice.

Best regards, Adjo

Answer №1

Utilizing Regular Expressions

var arr = ["3", "3-1", "3-15", "3-", "3-10", "3-100"];
var reg = /^3(-100)?$/;
var result = arr.reduce((acc, val, ind) => {
  acc[ind] = reg.test(val);
  return acc;
}, []);
console.log(result);

Answer №2

To find specific parts within a string, you can split the string and then use Array#includes.

let text = "2-50",
    segments = text.split('-').map((_, index, arr) => arr.slice(0, index + 1).join('-')),
    keywords = ["2", "2-3", "2-10", "2-", "2-20", "2-50"],
    outcome = keywords.map(term => segments.includes(term));
    
console.log(outcome);

Answer №3

This code snippet demonstrates a backward-compatible solution:

var numbers = ["3", "3-1", "3-15", "3-", "3-10", "3-100"];
var searchA = "3";
var searchB = "100";

for( var i=0; i< numbers.length; i++) {
  console.log( numbers[i] + " = " + checkValue(searchA, searchB, numbers[i]))
}

function checkValue( A, B, value ){
  var subNumbers = value.split("-");
  if( subNumbers[0] != A ) return false;
  if( subNumbers.length == 1 ) return true;
  if( subNumbers[1] != B ) return false;
  return true;
}

You can test this code on JS Bin

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

Iterating through an array in Javascript to create a new array filled with objects

Is there a way to iterate through an array of strings and convert them into an array of objects based on their values? For instance, if the array looks like this: [a,a,a,b,b,c,d] I aim to cycle through the array and create objects with key-value pairs t ...

Exporting data from JSON to a CSV file

I am attempting to find a solution for converting JSON objects into CSV files. I tried using a 'for...in' loop within another 'for' loop, but encountered an issue where the object properties and length are different. JSON data: [ {"n ...

What is the optimal method for iterating through every element in a string array?

Within my code, I am dealing with an array named var mya = ["someval1", "someotherval1", "someval2", "someval3"];. The goal is to have a function that receives an object with a property set to one of these values. Instead of simply iterating over the arra ...

Replace all existing content on the webpage with an exciting Unity game upon clicking

In an interesting experiment, I am trying to hide a secret href that, once clicked, has the power to wipe out everything on the page, leaving it temporarily blank before replacing it with a captivating Unity game that takes over the entire page. Let me sh ...

Link JSON filters to specific JSON nodes on the map

I have data representing nodes and links for a force directed graph. The links can have different numbers of connections between them, such as one, two, or three links: {"nodes": [{"id": "Michael Scott", "type": "boss"} ,{"id": "Jim Halpert", "t ...

How to expand a multidimensional array in Java by adding another element?

Looking for assistance with a method in Java that returns a 2-dimensional array. I need to add an additional element to the array but unsure of the correct syntax to copy it to a new 2-d array and include the extra element. Anyone familiar with this proces ...

Matching exactly two characters sandwiched between commas using a regular expression in Java

Imagine a scenario where we have a string like "3F, 4B, AA, A4B". What we need is a regex pattern that can effectively capture 3F, 4B, and AA. The condition is that there should be exactly 2 characters between the commas. However, if both characters are ...

Using Ajax to update a MySQL database with an array from jQuery

I need some assistance in updating a MySQL table using data from a jQuery array through AJAX. I've tried searching for similar issues without any luck, possibly due to my lack of familiarity with the correct terms in web development and coding. Allow ...

What is the best way to implement a dialog box that displays a website within it, all while keeping my SharePoint site running in the background?

For a while now, I've been working on SharePoint Online and trying to troubleshoot an issue without success. That's why I'm considering starting over with a specific section of my SP site from scratch. My current project involves creating a ...

inSession variable in express: set to false

i keep receiving inSession:false https://i.sstatic.net/4IW0f.png when attempting to log in, it is expected to return true. I am utilizing express session, in combination with postges and sequalize. I have logged the state values and they are being ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

Mention of a constant character pointer array

Trying to avoid repetition in code for 5 different arrays, currently working with 3 arrays: const char *FirstList[2] = {OPT_1, OPT_2}; const char *SecondList[2] = {OPT_1, OPT_2}; const ch ...

What is the best way to retrieve the value of a nested object within an object that has an integer property in JavaScript?

hello = [ { 0: { symbol: "asdf" , name:"adad"} }] In JavaScript, how can you access the symbol property in the 'hello' array? When you run console.log(hello[0]), it will output { symbol: "asdf" , name:"adad"}. However, if you try to access it u ...

Utilize Jquery to transform 3 arrays into separate objects distinguished by unique IDs

Recently, I've been experimenting with a very simplistic jquery admin area menu. My goal is to have jQuery create 3 identical menus with different IDs. I was able to accomplish this by creating a function and calling it three times with various variab ...

Overlaying content in a strategic and effective manner is key to maximizing

<div id="container"> <div>HEADER</div> <div>CONTENT</div> <div>FOOTER</div> <div><textarea></textarea></div> </div> <button>activate overlay</button> #cont ...

hiding form fields using javascript

As a beginner in javascript, I am facing a challenge with a set of checkboxes in an HTML form. These checkboxes are generated dynamically from a python script. Among them, there is a checkbox labeled "N/A" that I want to hide automatically when any other c ...

Get a C-string from a local function that returns a C++ string value

Is the following code snippet guaranteed to work as intended, with no errors? #include <string> #include <iostream> using namespace std; string getString() { char s[] = "Hello world!"; return s; } int main() { cout << getSt ...

What steps should I follow to create a JavaScript file incorporating jQuery?

As a newcomer to JavaScript and JQuery, I come from a background in basic C++ where I enjoy including header files and calling functions from there to maintain clean code. Now that I want to create a new JavaScript file, how can I ensure that I am able to ...

Displaying two distinct tables utilizing ng-repeat by employing customized directives

I'm facing an issue with a custom directive that generates tables and is appearing twice on my index page. The data for these tables comes from the $scope.globalrows variable. Even though globalrows contains 2 arrays, it always displays the second arr ...

Is there a technique to block small increments in a Time Input field?

Currently in the process of developing a tool to automate task scheduling within an Angular app. I am looking for a way to restrict the user's input when selecting the hour for task execution without having to install a complex input management packag ...