Sort through an array using various prefixes and suffixes as filtering conditions

I have come across various questions and answers related to this particular issue, but most of them involve using the includes or indexOf methods.

The problem at hand is how to filter an array (names in this scenario) using two different arrays - one with the startsWith criteria and the other with the endsWith criteria.

var names = ['BOB','CATHY','JAKOB','AARON','JUSTICE','BARBARA','DANIEL','BOBBY','JUSTINE','CADEN','URI','JAYDEN','JULIE']
startPatterns = ['BO','JU']
endPatterns = ['EN','ICE']

//res = ['BOB','JUSTICE','JUSTINE','JULIE','JAYDEN','JUSTICE']

It is clear that using

names.filter(d => d.startsWith(startPatterns))
is not a feasible solution as startPatterns is an array and not a string. The current approach I attempted is not only ineffective but also very slow:

res=[]
names.forEach(d => {
  endPatterns.forEach(y => d.endsWith(y) ? res.push(d) : '')
  startPatterns.forEach(s => d.startsWith(s) ? res.push(d) : '')})
console.log(res)

Answer №1

If you want to filter an array of names based on certain patterns, you can utilize Array.prototype.some method with pattern arrays:

const filteredNames = names.filter(name => (
  startPatterns.some(pattern => name.startsWith(pattern)) ||
  endPatterns.some(pattern => name.endsWith(pattern))
))

This code snippet checks if a name begins with any of the start patterns or ends with any of the end patterns to include it in the filtered array.

Answer №2

If you want to filter names based on specific patterns, you can use either a regular expression or an array method approach.

var names = ['BOB','CATHY','JAKOB','AARON','JUSTICE','BARBARA','DANIEL','BOBBY','JUSTINE','CADEN','URI','JAYDEN','JULIE'],
    startPatterns = ['BO','JU'],
    endPatterns = ['EN','ICE'],
    regexp = new RegExp(`^(${startPatterns.join('|')})|(${endPatterns.join('|')})$`),
    result = names.filter(s => regexp.test(s));

console.log(result);

An alternative method is to use an array with predefined methods and values to filter the names.

var names = ['BOB','CATHY','JAKOB','AARON','JUSTICE','BARBARA','DANIEL','BOBBY','JUSTINE','CADEN','URI','JAYDEN','JULIE'],
    patterns = [['startsWith', ['BO','JU']], ['endsWith', ['EN','ICE']]],
    result = names.filter(s => patterns.some(([k, values]) => values.some(v => s[k](v))));

console.log(result);

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

Looking to switch up the thumbs-up button design?

I am a beginner in using jquery and ajax, and I need some assistance. How can I incorporate this jquery code into my logic: $('.btn-likes').on('click', function() { $(this).toggleClass('liked'); }); Can so ...

Utilize Vue Component by assigning a computed property to the data source

Trying to assign a computed property value to a component's data in order to fetch and manipulate localStorage data. After mounting the component, I want to monitor changes in the localStorage. If my key is updated, I need to retrieve the new value, ...

The 'Cross domain jQuery Ajax request using JSONP' triggered an error: SyntaxError - Unexpected token : appeared on the screen

I've been struggling to extract information from the steam api, encountering persistent difficulties due to the error mentioned above. Below is the snippet of code I have been utilizing: var steamurl = "https://api.steampowered.com/IDOTA2Match_570/Ge ...

JkMegaMenu drop-down menus in Chrome are shifting to the left when the window is resized

Currently, I am utilizing the JKmegamenu plugin to incorporate a megamenu into a website that is currently under development. The megamenu functions properly and has an attractive appearance. However, there seems to be an issue where the drop-down divs shi ...

Maintaining the selected option on page refresh with React Remix

I have a dropdown menu with 2 choices (en, no) for switching the language when onChange event occurs. To save the selected language, I am using localStorage. Due to the server-side rendering in Remix, direct access to localStorage is not possible. Therefo ...

What is the process for attaching an iterator to the name value of every element within a cloneNode?

Consider the following scenario: <div id="addNewMenuElementPart2"> Numerous elements with a name attribute are present here. </div> <div id="addNewMenuElementPart3Optional"></div> Additionally, t ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

Is there a way to bypass the "Error: Another application is currently displaying over Chrome" message using Javascript or Typescript?

Can the "Another app is displaying over chrome error" be bypassed using JavaScript or TypeScript? Error Message: https://i.stack.imgur.com/iSEuk.png ...

Troubleshooting issues with JavaScript events in order to effectively implement popovers

I am facing an issue on a webpage that contains a significant amount of JavaScript. The Twitter bootstrap's popover widget is not functioning as expected. Specifically, when I hover over the icon that should trigger the "popover," nothing happens. I h ...

Encountering a 404 server error on Azure Node.js web app while running AngularJS 1.6.x with lengthy URLs

My current setup includes two azure web apps deployed with a node.js express server and using angularjs (1.6.x) for the MVC (ui-router). One web app links directly to the other, passing an access token in the query params for authentication. Everything run ...

Styling with CSS: Using a Base64 Encoded Image in the Background URL

Can a Base64 encoded image be loaded as a background image URL without exposing the actual encoded string in the page source? For example, if a Node API is used to GET request at "/image", it returns the serialized Base64 data. res.json("da ...

"Integration error: specified token_name parameters are invalid." FORTPAY INTEGRATION

I have been following the instructions provided by payfort in their email and referring to the Merchant Page 2.0 documentation for integration with nodejs. Despite sending all the necessary parameters in the request body, I encountered an issue where the T ...

Issue with Mouse Hover not functioning properly across various 3D objects

Trying to create a 3D line chart? Check it out Here Currently, the points and lines are working fine. However, I only want to detect mouse hover on the points (spheres) and not on the lines or grid. To achieve this, I have segregated all elements into dif ...

Displaying JSON data dynamically by iterating through it in a loop

While working with JSON data in a loop, I noticed that the code quality does not meet my expectations. I have a feeling that I might be missing something in my approach. $(function(){ $.getJSON('data.json', function(data){ let content ...

Utilizing Jquery for ASP.NET, an AJAX call dynamically populates a list

My user interface is designed to populate a select dropdown menu using data retrieved from a database through an AJAX call. The C# web method responsible for this operation is structured as follows: private static List<List<string>> componentT ...

Using Angular Directive to create a customized TreeView

Although I am still relatively new to Angular, I need to make some modifications to a treeview directive that I found on NgModules. The existing code looks promising, but I want to customize it to include the ability to add, delete, or modify items. You c ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

Having Trouble with Form Submission Button Across Different Web Browsers

Having some trouble with my form - all fields are properly closed with tags, but when I click the submit button, nothing happens. The page is loaded with code, so here's the link for you to check it out. Unfortunately, right-click is disabled, so ple ...

The functioning of JavaScript's ajax capabilities

Need some help with a coding issue I'm facing. Can anyone provide suggestions for improving my code? I've come across a situation where the table is not updating when using a certain piece of code. However, upon further inspection, I found that ...

What is the best way to show search suggestions on Google Maps autocomplete once three characters have been entered?

While integrating google-maps into my react app, I encountered an issue with the autocomplete feature. I would like the location search to display options only when at least 3 keys are entered, but Google maps autocomplete starts showing options with jus ...