JavaScript: Check array before adding new item to avoid duplicates

Is there a way in JavaScript to determine if an item already exists in an array? I am using the following code to add items to my array:

    const booked_hours = [];
    for (let i = 0; i < apptid_set.size; i++) {
        const book_hours = [...book_times][i].split(" ");
        booked_hours.push(book_hours[2]);
     }
     //alert(booked_hours);

The code works fine, but I want to ensure that there are no duplicate items in 'booked_hours'. Any suggestions on how to achieve this?

Answer №1

If you're unsure about the content being added to the scheduled_times array, this solution may need some adjustments, but here's a suggestion for you to consider.

 const scheduled_times = [];
    for (let j = 0; j < apptid_list.length; j++) {
        const sched_time = [...appt_times][j].split(" ");
        if (!scheduled_times.includes(sched_time[2])) {
          scheduled_times.push(sched_time[2]);
        }
     }

Answer №2

If you're looking to optimize your code for managing booked hours, consider utilizing a set instead of an array.

const booked_hours = new Set();
for (let i = 0; i < apptid_set.size; i++) {
    const book_hours = book_times[i].split(' ');
    booked_hours.add(book_hours[2]);
}

To easily convert the set back to an array, simply use [...booked_hours]

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

Can a 2D Numpy array be sorted in a way that resembles matching characters in a dictionary?

I need to arrange them according to the following rules: Firstly, it will check the '0th' column. If all values are different, the rows will be sorted by interchanging their positions up and down. If the '0th' column contains the same ...

Ignore missing values when performing an upsert operation

I'm currently utilizing pg-promise to manage my Postgres queries, but I've hit a roadblock with the following query conundrum: My goal is to develop a single method that can batch upsert multiple rows simultaneously. Here's the code snippet ...

Exploring the possibilities of custom layouts for specific routes within the pages directory in Next.js

I am interested in incorporating layout-based routing within my project's pages directory. I want to find a way to have a specific file, like the _app.tsx, that can only affect the files located inside a particular folder. This setup would operate si ...

What is the best way to present retrieved JSON data from a database in Node.js without using the JSON format?

Here is the code snippet: var http=require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var ejs = require("ejs") var bodyParser = require(&apos ...

When was Chrome first updated to include timezone offset support for Intl.DateTimeFormat()?

My experience with Chromium 121 has been positive using the Intl.DateTimeFormat as shown below: new Intl.DateTimeFormat('en', { dateStyle: 'long', timeStyle: 'long', timeZone: '+0500', }).format ...

The array functions properly when handwritten, but fails to work when loaded from a text file

I have been developing a password recommendation script that aims to notify users when they are using a commonly used password. In order to achieve this, I decided to load the list of common passwords from an external text file. However, it seems that the ...

Issue encountered with Matrix Multiplication: mismatches in data types (float to int)

Here is the code I have written for Matrix Multiplication: import java.util.*; class MatrixMultiplication{ static float[][] multiplyMatrix(float[][] a, float[][] b){ float[][] result = new float[a.length][b[0].length]; for(int i = 0; i < a.le ...

Express Session doesn't remove the variable assigned

While developing a web application using Node Express, I encountered a simple issue in my new project. Despite setting a session variable to null, the old session data is still being called. Seeking assistance to resolve this issue. I utilized express-ses ...

Send a string variable from PHP to a JavaScript function

Struggling to transfer a string from a PHP page to a JavaScript function on another page. This is for showing a message after checking if the item being added already exists in an array. I've attempted using quotes and not using quotes in the alert s ...

Why do I keep encountering a null window object issue while using my iPhone?

Hey there! I've got a React game and whenever the user loses, a new window pops up. const lossWindow = window.open( "", "", "width=500, height=300, top=200, left = 200" ); lossWindow.document.write( & ...

Automated Testing with Robot Framework: Utilizing Javascript to Click on a Button

Inspecting the web page <span jsslot=""> <button class="LkLjZd ScJHi IfEcue HPiPcc KXT7c" jsaction="click:yTqzwd" jsname="HxVe9c" autofocus="">Click Here</button> </span> I am tryin ...

Encountering a problem with controlling the number of splits allowed

I am encountering an issue with splitting my string using the code below. splitter.map((item1) => { let splitter1 = item1.split("=")[0].trimLeft(); let splitter2 = item1.split("=")[1].trimRight(); }); The content of item1 is as fo ...

Trapping an iframe refresh event using jQuery

I am trying to dynamically load an iframe using jQuery. Here is my code: jQuery('<iframe id="myFrame" src="iframesrc.php"></iframe>').load(function(){ // do something when loaded }).prependTo("#myDiv"); Now, I need to capture th ...

Retrieve targeted row or fields from a CSV file using PHP as though the CSV were a PHP array

My PHP skills were put to the test when I tried to replicate a PHP array using a .csv file. It seemed like a simple task at first, but I ran into some difficulties. Initially, I created a PHP array like this: $shop = array (); $shop [0] = array ('na ...

How can I make the type of a variable output be determined by an input that assigns a variable to a type within a function in Swift 5?

It was a bit confusing for me to use fread(), so I created a file reading struct with data, offsets, and reading methods. Now that it's working, I want to add a method to extract values from an n x m matrix and create a new matrix. (Similar to fread( ...

Ways to identify the moment jQuery datatable is initialized and populated with information

I am currently using the most recent version of jQuery datatables. I'm curious if there is a callback function available that triggers right after the data has been loaded and displayed in the table? While experimenting with a datatable in IE8, I hav ...

Clearing Input Values in Text Boxes, Dropdowns, and Checkboxes in ASP.NET MVC

Currently, I am working with Asp.net MVC 4 using C#. On one of my pages, I have a Text box, Drop down, and checkbox all together as search filters. There is also a "Clear" button to reset the values. When this button is clicked, I want the textbox value to ...

Activating the change event in jQuery: A step-by-step guide

Within my ASP.NET page, I have included a UserControl that contains a RadioButtonList. Whenever an item in the RadioButtonList is changed, I need to trigger the following jQuery function: $('#rdlUser').change(function (e) { alert("change fun ...

Launching in an Angular reactive form

When working with Angular reactive forms, I am facing an issue where I want to set a form control value using a property from a service. However, upon submitting the form, the value of the form control does not reflect the expected property value from the ...

Just for laughs: "The react-redux context value seems to be playing hide and seek; make sure to wrap the component in a <Provider> for it to show up!"

I encountered an issue while attempting to run a basic Jest test on a form React component: ● <LoginForm /> › clicking the validate button › should display page title ...