Add an element to an array and check if it is already present

Hey everyone! I've written some code and need help fixing it so that the if statement works properly when adding the same student. Thanks so much for any assistance!

class Student {
constructor(name, email, community) {
    this.name = name;
    this.email = email;
    this.community = community;
}

}

class Bootcamp {
constructor(name, level, students = []) {
    this.name = name;
    this.level = level;
    this.students = students;
}

registerStudent(studentToRegister) {        
    if (this.students.forEach(s => s.email === s.email)) {
        console.log(`The student ${studentToRegister.email} is already registered!`);
    } else {
        this.students.push(studentToRegister);
        console.log(`Registering ${studentToRegister.email} to the bootcamp ${this.name}.`);
    } 
    return this.students;
}

}

// Testing the code

// Creating new Bootcamps
const webDevFund = new Bootcamp("Web Dev Fundamental", "Beginner");
const fullStack = new Bootcamp("Full Stack Web Dev", "Advanced");

// Adding students to Bootcamps
const Max = new Student("Max", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91fcf0e9d1f7e8f0e3f5bffff4e5">[email protected]</a>", "PAP");
const Bird = new Student("Bird", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15777c677155736c7467713b7b7061">[email protected]</a>", "Cap-Haitien");
const Yayad = new Student("Yayad", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d544c544c496d4b544c5f4903434859">[email protected]</a>", "Cayes");
const Meg = new Student("Meg", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="39545c5e795f40584b5d17575c4d">[email protected]</a>", "Miami");

// Verifying registrations
webDevFund.registerStudent(Bird);
webDevFund.registerStudent(Max);
fullStack.registerStudent(Yayad);
fullStack.registerStudent(Meg);
fullStack.registerStudent(Yayad);

Answer №1

You might want to consider using Array.some instead:

if (this.students.some(s => studentToRegister.email === s.email)) {
    console.log(`The student ${studentToRegister.email} is already part of the list!`);
}

Furthermore, think about implementing Map or Set for this scenario:

const map = new Map;

if (!map.has(student.Email)) {
    map.set(student.Email, student);
}
const set = new Set;

if (!set.has(student)) {
    set.add(student);
}

Answer №2

Your current code:

    if (this.students.forEach(s => s.email === s.email)) {

The improved code:

    if (this.students.find(s => s.email === studentToRegister.email)) {

It's important to understand the difference between using forEach and find in arrays. The find method returns a matching value, while forEach does not return anything (thus is falsy).

Keep in mind that if you don't have multiple instances of the same student details, you can compare the student objects directly instead of just checking the email address.

Answer №3

I am unsure of the specific reason for the program crashing. It would be beneficial if you could share error specifics. However, upon initial inspection, there seems to be a potential bug in the code:

if (this.students.forEach(s => s.email === s.email)) {

The condition s.email === s.email will always result in true.

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

Steps to update a JSON file when running a query:

Is there a way to update the json file results.json without having to execute the demo.php file? demo.php <?php header("content-type:application/json"); require_once("dbConnect.php"); $sql = "SELECT id ,,fullname ...

Utilizing JavaScript to send various arrays to a .NET web service

Hey everyone, I'm currently facing an issue with posting multiple arrays to a .net web service and here is the signature of the web service. <WebMethod()> _ Public Function Lib_Processor(ByVal w_vendor As String(), _ ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

I am finding that the text I am creating using context.fillText keeps getting distorted within the canvas

I am attempting to place text inside a canvas element. The HTML markup for the canvas is as follows: <canvas id="leaderboard2" style="position: fixed; right: 1250px; top: 140px; width: 230px; height: 330px;"></canvas>. Des ...

Using JavaScript to parse an XML document on a WAMP server

I am a beginner in the field of web development and currently struggling with parsing an XML document using JavaScript on WAMP server. I know that both the web page and XML file need to be on the same server for it to work. I tried placing both the PHP and ...

Is it possible to combine Sprites as Geometries in Three.js?

My dilemma involves placing labels with the names of cities on a terrain. However, once the number of labels exceeds ten, the frames per second drastically decrease. I've tried implementing the code provided at My code looks something like this: va ...

Form submissions are not saving checkbox answers

As a beginner, I'm struggling to save the checkbox answers on the page after submission. The code below is quite lengthy (checkboxes start at 314). I have a feeling that I might be missing a piece of code, but I just can't seem to pinpoint what i ...

Express POST request body is required

I am starting to learn nodejs and express, and while reviewing some code I found this interesting snippet. Can someone please explain what it means and how I can send a POST request to it using cURL? There are no specified data fields. app.post('/&apo ...

Utilizing an array of c-strings with the pass by pointer method proves to be ineffective

When trying to assign new values to an array of C strings using the pass by pointer method, things do not go as expected. Within the "LettersToCapital" function, everything seems fine - new values are successfully assigned to the C-string array. However, ...

Deactivating controls while displaying the loading bar in AngularJS

I'm currently working on a web application using AngularJS. I want to incorporate a loading bar to signify long data load times from the server. To replicate heavy data loads, I am utilizing $timeout to trigger the loadbar when the operation begins a ...

Locate an item within a JavaScript array

Similar Question: Javascript - Checking for value in array Can you spot the issue here? var zipCodes =(['90001','90002','90003']); Determine if a specific value is present in the array zipCodes if('90001' in ...

Delete the tag that comes before

Is there a specific tag like: <p id="name" onclick="javascript:var ele=context(this);">sumtext here</p><br> <p id="name" onclick="javascript:var ele=context(this);">newtext here</p><br> <script ...

The disabled feature doesn't seem to be functioning properly with the <i> tag when using Font Awesome icons

I've designed a plunk where I'm trying to validate a form with a button featuring a font-awesome icon. The text field is mandatory and I'd like to disable the icon if no data has been entered. However, it seems that ng-disabled doesn't ...

Assigned a gender to my _id using the first name and last name

Hello, I am attempting to generate an _id in mongodb using a combination of the first name and last name. However, I'm encountering a problem with this process. My desired format for the id is like this: '_id':'midoxnavas' where &a ...

Encountering an issue with my node configuration while working on a Discord bot

Attempting to develop my own Discord Bot has presented me with a challenging error that I am struggling to resolve: internal/modules/cjs/loader.js:968 throw err; ^ Error: Cannot find module './commands/${file}' Require stack: - C:\Users&bso ...

Having trouble retrieving the keyword property within a Vue.js promise

Struggling with an async validation process in Vue.js where I need to globally access the $axios instance, but encountering failures Validator.extend('async_validate_job_type', { getMessage: field => `The Name already exists`, val ...

An invalid argument error occurred in line 4618 of jQuery version 1.4.2, with a value of NaNpx specifically

There seems to be a common exception occurring in jQuery.extend as follows: Error Message: Invalid argument. Line Number: 4618 Character Position: 4 Error Code: 0 URI: The issue I am facing is that amongst our development team, only my machine is experie ...

Building a custom shadowDOM with a dynamic bootstrap dropdown menu using JavaScript

As I work on developing a Chrome extension, I found myself in need of incorporating the split-button feature provided by Bootstrap within a shadow DOM. Despite my efforts, I have not been able to find clear guidelines on how to achieve this. Can anyone pro ...

What is causing the unexpected behavior of deferred.resolve in the q manual?

I can't seem to grasp this concept and it might be a silly question. Let's analyze the code snippet below: function throwError() { throw Error("can't touch this."); } var def = q.defer(); def.promise.then( function() { co ...

Generating conference itinerary - establishing agenda function (Sequelize)

const _ = require('lodash'); const Promise = require('bluebird'); const Sequelize = require('sequelize'); const ResourceNotFound = require('./errors').ResourceNotFound; const ResourceAccessDenied = require('./er ...