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' },
];
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' },
];
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.
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
})
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)
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());
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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"> ...
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 ...
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 ...
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 } ...
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 ...
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 ...
import React from 'react'; export default class CreateNote extend React.component { constructor(props) { super(props); this.state = {note:{title:" ",content:" "} }; console.log(this.state); ...
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 ...
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, ...
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 ...
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 ...
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 ...
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 ...
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 ...