Examining which string, if any, in an array, serves as a superstring for another string in the array

Let me share with you this scenario:

var eventTypes = ['#course', '#bundle'];
var customEvent = ['#coursebar']

I am looking to determine if any of the strings in customEvent is a superstring (starts with) any value from the strings in eventTypes. If so, I want to return the first matching value.

I've experimented with using find and includes, but haven't been able to achieve the desired outcome. Most examples I came across dealt with comparing just one string against an array.

To make things clearer, here are some expected results:

var eventTypes = ['#course', '#bundle'];

// SCENARIO 1
var customEvent = ['#coursebar'] // should return '#coursebar'

// SCENARIO 2
var customEvent = ['#foo'] // should return undefined

// SCENARIO 3
var customEvent = ['#coursebar, #coursebaz'] // should return either '#coursebar' OR '#coursebaz'

I'm aware that accomplishing this using for loops is possible, but I'm curious if there's a more concise and modern approach available.

Answer №1

To determine if the elements in eventTypes are present in customEvent, you can utilize the combination of array#find and array#some.

const eventTypes = ['#workshop', '#training'],
  customEvent = ['#workshopbar, #trainingbaz'],
  result = customEvent.find(event => eventTypes.some(type => event.startsWith(type)));
console.log(result);

Answer №2

This code snippet appears to solve the issue:

customEvent.find((x) => eventTypes.find((y) => x.startsWith(y)))

Answer №3

To achieve the desired outcome, utilize filter in combination with some as demonstrated below:

let matches = customEvents.filter(event => eventTypes.some(type => event.startsWith(type)))

You can then access any specific element from the array matches

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

What is the best way to transition from the splash screen to the onboarding screens?

Welcome to SplashScreen.js I am here to help you display a splash screen that will disappear after a set timeout, and then smoothly navigate you to the Onboarding Screen. import React from 'react'; import { View} from 'react-native'; ...

Using the className prop in a React Component

Struggling to assign a classname to the material-ui Button component. Here are my failed attempts: Attempt 1: attributes.map((attribute, index) => { const classString = 'classes.button' + index; console.log(classString) return ( &l ...

Utilizing NodeJS on an alternative drive other than the system drive

Situation: On my Windows 8 x64 machine, I have NodeJS installed on the C drive. QUnit is also installed globally using the command npm install qunit -g. The issue at hand: When I try to reference QUnit by using var q = require('qunit'); while ...

Performing JSON data extraction and conversion using JavaScript

Hello! I'm working with a script that converts data into an array, but I want to enhance it so that I can extract and convert data for each object (arb, astar, aurora, avax, baba, bsc, etc.), as shown in the screenshot. Here is the current script tha ...

Finding the iframe document on Chrome

I've been attempting to dynamically adjust the height of an iframe based on its content, but I'm facing issues in the latest version of Chrome. In Chrome, 'doc is undefined' error is showing up. Surprisingly, everything works perfectl ...

Why isn't my JavaScript Alert displaying a string message?

I'm feeling a bit puzzled and I have a feeling there must be an easy solution, so please lend me a hand. Here's the code snippet that is causing me some confusion: $new = "1"; <script language="javascript"> alert(<?php echo $new; ...

I am having difficulty converting the ajax response data stream into a CSV file

I'm trying to convert the ajax response, which contains a stream of data with some unknown characters (possibly a blob, byte stream, or byte array) into a CSV file. However, when I download the file, it still has the same garbled data. $.ajax({ url: ...

How can I clear all checkboxes when the checkbox with id "checkAll" is selected?

Is there a way to uncheck all checkboxes when the checkbox with id="checkAll" is checked? In my demonstration, when a user checks the checkbox with id="checkAll", all checkboxes are also marked as checked. However, I actually want it so that when the che ...

"Initiate an Ajax call in Full Calendar before an event is displayed on the calendar

I need guidance on how to integrate ajax calls with the Full Calendar documentation. Specifically, I want to make an ajax call to a WordPress database before each event is rendered on the calendar. The response from the call will determine the color of the ...

how to make a post request to an API using Next.js

I am attempting to make a request to the Exist API using next.js and the backend is in PHP. I am trying to send a post request (using Axios) with data and retrieve the response. How can I manage this API in my code? I have read that I need to include som ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

What is the best way to link a URL ID to a specific piece of content stored on

Is it possible to display a product without creating separate html pages for each one using unique IDs? I prefer the layout style of Pinterest. For example, with a URL like /product/12345 When a user clicks on /product/12345, the content should be rende ...

Function URL.createObjectURL is not defined in Reactjs

I am currently working on a loadfile function that is supposed to load an image after uploading. However, I am facing an issue with converting it to get its URL path. Whenever I try to do so, I encounter an error saying "URL.createObjectURL is not a func ...

Guide on including the angular value (id) in conjunction with repeating data-target for executing a function

I have the following code snippet. Now, I am trying to pass a dynamic AngularJS variable, specifically the id of a repeating list. The button in question is used for deactivation purposes, and upon clicking it, a confirmation box pops up. Upon confirming ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Is it possible to use a variable in JSX within a map function to modify inline CSS styles?

I have a map function that loops through an array and generates divs on the DOM for each color item. The array consists of hex values representing different colors (e.g. #1a703f). The goal is to set the background of each div to match the corresponding co ...

What is the best way to differentiate between UIImages stored in arrays?

I'm currently developing an application that requires the ability to compare values within an array or set. For example, let's consider the scenario where I have constants and an array like the following: let blueImage = UIImage(named: "blue") ...

What is the proper way to assign labels to an array?

I have a table in my Database where my script is storing its values. I am trying to achieve the following task: if a "description" already exists, I want it to display once but count up all the duplicate rows. The code below accomplishes what I need, howev ...

Discover the latest CSS styles and HTML attributes that impact the dimensions of an image

I am in the process of developing a custom jQuery plugin that will enable me to easily change the "src" attribute of an image on my website based on the width of the browser. However, I've encountered an issue where when the new image is loaded, the ...

Concealing buttons and Enabling others using ajax

I am facing a situation where I need to modify the behavior of a modal window on my webpage. The modal currently has two buttons for confirmation and cancellation, as shown in the code snippet below. Inside this modal, there is a <div class = "resp"> ...