Determine if the element in a string is present in an array using TypeScript

I am dealing with the string:

"0,2,4,5,6"

How can I verify if these numbers exist in an array?

let daysweek = [
    { id: '0', name: 'Sunday' },
    { id: '1', name: 'Monday' },
    { id: '2', name: 'Tuesday' },
];

Answer №1

Develop a set containing the IDs from the array daysofweek, enabling easy verification of whether an ID exists in the set.

let daysweek = [
   { id: '0', name: 'Sunday' },
   { id: '1', name: 'Monday' },
   { id: '2', name: 'Tuesday'   },
];

let days = "0,2,4,5,6";

let set = new Set(daysweek.map( item => item.id ))
let found_days = days.split(",").filter( day => set.has(day) );

console.log(found_days);

This solution runs in O(N) time complexity. In comparison, AlwaysHelping's and MarkCBall's solutions have a time complexity of O(N^2), which can lead to significantly slower performance as the size of the daysweek array grows.

Answer №2

If you want to extract ids from a string and compare them with a predefined list of ids, you can use the Array#map method along with the split function.

The split() function will split the string and convert it into an array, removing any commas.

By using map, you can extract all the ids and store them in a variable. Then, you can compare these ids with the strings you have using the Array#forEach method.

Live Example:

let daysOfWeek = [{
    id: '0',
    name: 'Sunday'
  },
  {
    id: '1',
    name: 'Monday'
  },
  {
    id: '2',
    name: 'Tuesday'
  },
];

let str = "0,2,4,5,6".split(',') // Split the string
let  daysID = daysOfWeek.map(day => day.id) // Store the ids
str.forEach(function(x){    
    let found = daysID.includes(x)
    console.log(x + " = " +found) // Display true or false for each found id
})

Answer №3

const weekDays = [
    { id: '0', name: 'Sunday' },
    { id: '1', name: 'Monday' },
    { id: '2', name: 'Tuesday' },
];
const daysOfWeekIds = weekDays.map(obj=>obj.id)

const numsInArray = "0,2,4,5,6".split(",").every(num=>daysOfWeekIds.includes(num))
console.log(numsInArray)

Answer №4

I want to express my gratitude to everyone, as I have come across an example that fits perfectly with what I was looking for

daysweek2 = [
     'Sunday',
     'Monday',
     'Tuesday',
     'Wednesday',
     'Thursday',
     'Friday',
     'Saturday',
];


function initializeDays() {
   return "0,2,4".split(',')
      .map(key => this.daysweek2[key]).join(',').split(',')
}


console.log(this.initializeDays());

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

Browsing through json subgroups

Having issues with filtering an array within my JSON file. Filtering the main array works fine, but I'm struggling to filter subarrays. This is the structure of my JSON file: [ { "id": 1354, "name": "name", "type": "simp ...

In one application, there are two connections established with mongoose. The purpose of the second connection is to establish a dependency on the

Seeking advice: I am facing an issue where I need to establish two separate connections to the database. The first database contains login information, while the second holds all other relevant data. Can this be achieved through integration of Node.js, m ...

Issue "cannot update headers after they have been sent"

I've been working on a node.js application to retrieve movie listings using the omdb api. However, I'm encountering an error when attempting to access the /result route. The error message is as follows: Error: Can't set headers after they ar ...

What is the best way to retrieve data from a JavaScript function and store it in a user's custom meta field using PHP?

Currently, I am utilizing a platform that automates the device registration process for my users through Onesignal. Upon user login, I invoke the function by using gonative_onesignal_info(); within script tags (the full function is provided below). This s ...

Steps to integrating an interface with several anonymous functions in typescript

I'm currently working on implementing the interface outlined below in typescript interface A{ (message: string, callback: CustomCallBackFunction): void; (message: string, meta: any, callback: CustomCallBackFunction): void; (message: string, ...m ...

What is the best way to apply various styles to a single CSS class?

I'm in the process of implementing a dark mode feature on my website, and I want to do it without using any boilerplate code. My plan is to create a .darkmode class in CSS, apply styles to it, and have JavaScript add the darkmode class to the <bod ...

Tips for sending arguments to react-highcharts?

While browsing through the documentation, I noticed that I can pass config in a certain way: render() { let config = this.config; return ( <div className="column"> <div className="ui segment"> ...

Identify individual cells within a row that share the same ID

I am facing an issue with detecting which cell of a textarea or input text is being changed using the onchange method in my table. The script I have triggers an alert message only for the first row of the table td. For instance, if I add text to the 2nd r ...

Setting the initial state for a React toggle custom hook

After clicking a chevron button, an accordion component below it expands to display its children components. The goal is to ensure that each chevron button operates independently so that only the clicked button expands its related accordion. Upon initial ...

Using Typescript to create mapped types with optional parameters

I am currently working on implementing a mapped type that has some required parameters and some optional ones. While I have successfully implemented the required parameters, I am facing issues with utilizing the optional ones. type Foo = { foo: string } ...

Using :global() and custom data attributes to apply styles to dynamically added classes

Currently, I am working on creating a typing game that is reminiscent of monkeytype.com. In this game, every letter is linked to classes that change dynamically from an empty string to either 'correct' or 'incorrect', depending on wheth ...

Leveraging external objects in Vue.js computed functions

Can Vue's computed property be used with an external object? Let's consider the following code example to illustrate the idea: <!-- Vue file --> <template> <div>{{data.auth}}</div> </template> <script> i ...

I need the title to be filled with the input data and the content to be filled with the textarea data

import React from 'react'; export default class CreateNote extend React.component { constructor(props) { super(props); this.state = {note:{title:" ",content:" "} }; console.log(this.state); ...

form data not being populated in req.body

My attempt at submitting a POST request to my nodejs (express) server is not populating any data from my form in the req.body. I have searched for solutions and found that many suggest moving the bodyparser before the routes and ensuring form fields have n ...

The API is invoked twice

I have developed an app centered around hockey statistics. However, I am facing a challenge with the endpoints as I only have access to team and player stats. My current approach involves calling the API with the first team, selecting the top 2 players, ...

How can I prevent buttons from being created using ngFor in Angular?

I need help with creating an HTML table that includes a cell with a button and a dropdown generated using ngFor. How can I disable the buttons (generated via ngFor) if no value is selected from the dropdown? Here's what I have tried so far: In my App ...

How to Load and Parse CSV Files in Meteor.js

What is the best approach for reading CSV files into a Meteor app from a filesystem path located within the /private directory? I came across the fast-csv package, which is also available as a Meteor package. However, I am unclear on how to create a creat ...

output the elements of a list of strings

I am trying to generate a list of strings based on a given list of numbers. For example, let's say the input list is list=[1,2,5,25,6] Expected output: ['Odd', 'Even', 'Odd, multiples of 5 and odd', 'multiples o ...

Having trouble connecting angular repository data with promise

I have been trying to implement the repository pattern in my Angular application. I can see that the JSON data is successfully retrieved over the network when I call my repository, but I am facing issues with binding it to my view. I have injected the rep ...

Choosing a specific column in an HTML table using jQuery based on the text within it

I have a table with a similar structure as shown below: <table> <c:forEach ...> <tr> <td>test</td> // this is the initial value <td>random value</td> <td>random value</td&g ...