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

Implementing an Ajax-based solution for multiple select filters

I have 4 select lists with the following IDs: price_sort, power_sort, area_sort, source_sort. I am using jQuery's .change() function to send POST data via AJAX in order to receive a response from the controller with sorted results. Javascript: ...

Tips for navigating libraries with Google CAJA

Is there a way to configure Google Caja to allow specific libraries to work without being sanitized? I have my own CAJA server and an application based on NodeJS. I'm providing users with code that is mostly related to charts and graphs, but certain ...

Using CSS sprites to style text links

I've been attempting to incorporate an image with various icons for text links in an unordered list, but I can't seem to display just one icon with some space next to it for the text. The code I have so far is: http://jsfiddle.net/XyVtq/2/ This ...

What is the process for loading an external file within an npm script?

Objective: Testing the linting process of specific components within the source code, without affecting all files. I want to streamline the linting process by running a single command that covers multiple folders specified in a configuration file: //pack ...

The Ajax request fails to execute properly following the invocation of the load() method

I am facing an issue where the div is not refreshing after subsequent ajax calls. It seems that only the first ajax call is working and after reloading the div, the ajax call stops functioning. $('.sequence_no').on("change", function () ...

Animate the background of a table cell (td) in React whenever a prop is updated

I have a dynamic table that receives data from props. I would like the background animation of each cell (td) to change every time it receives new props. I've tried creating an animation for the background to indicate when a cell is updated, but it on ...

What causes the empty gap to appear during animated transitions between two 'div' elements?

Is there a way to eliminate the white space in between elements during animation? Should I wrap both divs into another div to achieve this? I am using position-top to adjust my div animations. Could this be causing the issue? What other methods can you s ...

Using Bootstrap 4, create a responsive design that centers images within a div on mobile devices and positions them differently

I am currently working on a DIV that contains social media buttons. The code for this DIV is as follows: <div class="redes-sociales col-sm-pull-6 col-md-6 col-lg-push-4 float-right py-2"> <img class="img-rounded img-social" alt="f ...

Improved method for transferring Mongodb query information to Pug

I'm seeking a more efficient method of passing data to my index.js file in a web development application. With only about a month of experience in web development, I acknowledge that this challenge likely stems from my lack of expertise. Here is the w ...

align the p tag vertically next to the image

I'm struggling to get a p tag vertically aligned next to an image. The issue is that only the first line of text aligns properly. How can I make the text in the p tag wrap around the image while maintaining vertical alignment? Here is the HTML code: ...

What is the best way to iterate over an indexed attribute in PHP?

Here is my ajax code snippet: $.ajax({ type: "POST", url: "bee_sesi_edit.php", data: 'serv_ruang='+ serv_ruangx +'&who='+names +'&sesi_d1='+ sesi_d1 +&apos ...

Tips for creating a deepCss selector for an input Textbox in Protractor

When I attempt to use sendKeys in an input textbox with Protractor, the element is located within a shadow-root and there are three separate input textboxes. ...

The res.sendFile() function quickly delivers a 204 no content response

Currently, I am facing an issue with using Express' sendFile() function to send an image. The function does not seem to read my file at all and instead returns a 204 no-content response. Below is the code for my function/endpoint: @httpGet('/pri ...

Unable to drag and drop onto every part of a div element that has undergone a CSS transformation

Having trouble implementing a Drag & Drop feature. The droppable div is styled with CSS transformations, but the draggable div doesn't drop correctly on the right part of the box. If you'd like to take a look at the code and try it out yourself, ...

I require the flexbox children to be arranged in a regular manner

How can we set flexbox children to default layout behaviors? Let's make them behave like the disobedient kids they are. .wrapper { This should be a row } .column { Make all heights equal display: flex; } .child { Back to regular display...wit ...

Why does my ajax request show the result in the php file rather than redirecting to the html page?

I've developed a series of AJAX functions that retrieve data from a PHP file. However, one of the functions redirects to the PHP file to fetch data but fails to return to the HTML page for data insertion. Here is the code used to fetch a table from a ...

How do I resolve the issue of not being able to display the value for the slider range?

What do I need to do if I am unable to print the value for a slider range in my code? <?php $salary=array( 'type'=>'range', 'name'=>&apo ...

What steps should I follow to incorporate channel logic into my WebSocket application, including setting up event bindings?

I'm currently tackling a major obstacle: my very own WebSocket server. The authentication and basic functionality are up and running smoothly, but I'm facing some challenges with the actual logic implementation. To address this, I've create ...

Implement Ajax to validate a form directly within the <script> tag

I'm trying to incorporate validation and AJAX within the same <script> tag, but it seems that the AJAX functionality is not working properly. Can you help me understand if I'm doing this correctly? After checking the console, I encountered ...

Displaying a pop-up window containing information retrieved from the console output

Upon user input in the form on my web application, an scp and ftp process is initiated that takes around 2-3 minutes to complete. The result page consequently experiences a similar delay in loading. To enhance user experience and provide real-time updates ...