Is there a way to verify and send notifications when duplicate entries are added to my table?

Whenever a make and model are added using the "add" button, I need to ensure that there are no duplicates. If a duplicate is found, an alert should be displayed, and the entry should not be added to the table. Unfortunately, I have been unable to find a solution for this issue...

Below is the complete code for the beginner project I am currently working on. I apologize in advance if this post is unclear, as this is my first time posting here. Thank you all for your help.


<div>
    <div>Make: <input type="text" ng-model="make"></div>
    <div>Model:<input type="text" ng-model="model"></div>
    <button ng-click="add()">Add</button>


    <tr>
        <th>Make</th>
        <th>Model</th>
    </tr>
    <tr ng-repeat="car in cars" ng-click="rowClick(car)">
        <td>{{car.make}}</td>
        <td>{{car.model}}</td>
    </tr>


  <table class="table carsTable">
    <tr>
        <th>Make</th>
        <th>Model</th>
    </tr>
    <tr ng-repeat="car in cars" ng-click="rowClick(car)">
        <td>{{car.make}}</td>
        <td>{{car.model}}</td>
    </tr>


<script>
var carsApp = angular.module('carsApp', []);

carsApp.controller('carController', function ($scope){

    $scope.cars = [];

    $scope.add = function () {
        
        // Check for duplicates
        var isDuplicate = false;
        $scope.cars.forEach(function(item){
            if (item.make === $scope.make && item.model === $scope.model) {
                isDuplicate = true;
                return;
            }
        });

        if(isDuplicate){
            $scope.alert();
        } else {
            $scope.cars.push({
                make: $scope.make,
                model: $scope.model
            });
    
            $scope.make = null;
            $scope.model = null;
        }
    };

    $scope.rowClick = function(car){
        $scope.make = car.make;
        $scope.model = car.model;
    };

    $scope.alert = function(){
        alert('Already exists in table');
    };
}); 

Answer №1

To identify duplicate entries in your array, you need to compare each car object based on its make and model properties. One way to achieve this is by utilizing the Array.some method, which returns a boolean value indicating whether any element in the array meets the specified condition:

Within your add function:

var hasDuplicates = $scope.cars.some(car => car.make == $scope.make && car.model == $scope.model);

if (hasDuplicates) {
    alert("Car already exists");
} else {
    $scope.cars.push({
       make: $scope.make,
       model: $scope.model
    });
}

If you are unable to use arrow functions, you can achieve the same result using a traditional function declaration like this:

var hasDuplicates = $scope.cars.some(function(car) {
    return car.make == $scope.make && car.model == $scope.model;
}); 

Answer №2

 $scope.addToGarage = function () {
    let carToAdd = {
       manufacturer: $scope.manufacturer,
       model: $scope.model

    };
    let hasAlreadyAdded = $scope.garage.some((car) => angular.equals(car, carToAdd ));
    if (hasAlreadyAdded) {
        $scope.alert();
        return false;
    }
    $scope.garage.push(carToAdd);

    $scope.manufacturer = null;
    $scope.model = null;

  };

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

When attempting to utilize res.sendfile, an error arises indicating that the specified path is incorrect

I am facing an issue with my Express.js server and frontend pages. I have three HTML and JS files, and I want to access my homepage at localhost:3000 and then navigate to /register to render the register.html page. However, I am having trouble specifying t ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

When IntelliJ starts Spring boot, resources folder assets are not served

I'm following a tutorial similar to this one. The setup involves a pom file that manages two modules, the frontend module and the backend module. Tools being used: IDE: Intellij, spring-boot, Vue.js I initialized the frontent module using vue init w ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Issue with Google Charts - Chart is unable to render because data table has not been defined

Using Ajax, I attempted to set an Interval for my Google Chart, but unfortunately, the Chart is not being drawn. Instead, I repeatedly receive the error message: "Data table is not defined." every 5 seconds. If you want to see a screenshot of the error mes ...

Adjusting the Stripe Button to Utilize a Unique Button Class

I have a stripe button on my website and I want to add my custom class to it. I discovered that manually creating the CSS for it can work, but I prefer to maintain consistency across all buttons on my site by using my custom class. No matter what I attemp ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...

Utilizing Yii to Partially Render and Send JSON Response via AJAX

My current issue is regarding the return of data. When attempting to send the rendered partial view data from my controller to AJAX, the code provided below will be utilized. JQuery AJAX: $.ajax({ url: "<?php echo $this->createUrl('aj ...

React JS is having trouble rendering an object that contains a list as one of its elements

I've been attempting to display the P_words list element with React using map: const f_data = { key: 2412, reviewed: 100, rating:4, P_words: [{ word: "Coolx", freq: 5 }, { word: "Dumbf&quo ...

Calculating the width of fluctuating DOM elements in AngularJS

It seems like most of my Angular questions are just me overlooking something really silly, so let's hope that's the case here too. Currently, I am working on a directive to manage the scrolling of a wide list of thumbnails. While it was working ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

Unable to include query parameters in the nextjs dynamic route

I have a file called [slug].js. What I am attempting to do is add a query parameter to this dynamic route. Here's the code: await router.replace({ pathname: `${router.pathname}`, query: { coupon }, }, undefined, ...

Issue with Angular FormControl Pattern Validator failing to validate against regex pattern

My goal is to restrict a text input field to specific characters only. I am looking to allow: alphanumeric characters (a-z A-Z 0-9) 3 special characters (comma, dash, single quotation mark) : , - ' A few accented characters: à â ç è é ê î ô ...

Utilizing the Javascript code, the FaceBook API is able to retrieve posts specifically

I'm having an issue with a jQuery plugin that is supposed to pull posts from my Facebook Wall page. Currently, it is only retrieving status updates and not all the posts on the wall. Can anyone help me pinpoint where I am making a mistake? Here is th ...

Angular single page application with a sleek, user-friendly navigation bar for easy browsing

I have been attempting to solve the issue at hand without much success. As a newcomer to web development, I have been working on creating a basic app using angularjs and bootstrap. My pages are fairly sparse, consisting only of a few inputs and buttons t ...

Getting the value returned by http.request in an app.get method using express.js

When attempting to deliver data from an API on another domain using app.get, I am able to write the data to the console successfully. However, the data is not showing up on the page ('~/restresults'). This is the current code I have: app.get(&a ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

Toggle button color on click by using ng-click on a different button

As a newcomer to Angular, I am facing an issue. I have two buttons - button1 and button2. What I want is that when I click on button1, its color changes from green to red. Then, when I click on button2, the color of button1 should revert back to green. How ...

Determine which checkbox is currently selected in Vue and send corresponding data based on the checked status

A radio form that is conditionally disabled by another checkbox. One radio button can send either true or false and the other has an input that sends some data. How can I determine which radio button is checked and decide whether to send true/false or the ...