Ways to run a javascript command just a single time

I have a function that makes an HTTP GET request to compare a given value with elements in an array. If there's no match, I want to add the value to another array. The issue is that duplicates are being added to the array because of multiple loop iterations. Here is my code:

 $scope.fetchParcel = function()
     {

    $http({
            method: 'GET',
            url: '/infiniti/' + $scope.infinitiId, 
        })
        .success(function(a){

            angular.forEach($scope.parcels, function(parcel, key){
                    angular.forEach(parcel, function(par){


                        if(par == $scope.shipper_ref_no){
                            $scope.scans.push(parcel);
                            $scope.checked++;

                            $scope.parcels.splice(key, 1);

                        }
                        if(par != $scope.shipper_ref_no){
                            $scope.excludeds.push($scope.shipper_ref_no);
                        }


                    });

            });

        });

}

The part where it says

$scope.excludes.push($scope.shipper_ref_no);
correctly adds the shipper_ref_no to the array, but due to multiple elements in the array, it gets added multiple times when it should only be added once after confirming that no matches were found. How can I achieve this?

Example of the array:

 [
 -{
    id: 1
    t: "1122"
    srn: "23"
  }
 -{
    id: 2
    t: "234"
    srn: "23"
  }
 -{
    id: 3
    t: "dd"
    srn: "44"
  }
 ]

If my input is something like "444kkkddd" and it doesn't match any element, it adds "444kkkddd" to the array multiple times. I need it to be added just once. I understand why it happens, but I'm seeking a solution to handle this so it adds just one entry. I'm stuck.

Answer №1

You may want to maintain a record of ids that have been added:

var idList = {};

if(par != $scope.shipper_ref_no){
    if (!idList[$scope.shipper_ref_no]) {
        idList[$scope.shipper_ref_no] = true;
        $scope.excludeds.push($scope.shipper_ref_no);
    }
}

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

Run a JavaScript function multiple times in the code behind using C#

My challenge involves using a datatable and executing a JavaScript function for each row, with different values each time. For every row, the JavaScript function is executed and the result is sent back to the code behind using a web method. However, with ...

What is the best way to retrieve specific information from a group of data using Mongoose?

I need assistance with extracting the number from a collection that contains only a name and a number. I also want to either change the number or store it in a variable. How can I achieve this? let dataSchema = new mongoose.Schema({ name: String ...

Several directories for viewing in Node.js with Express

I have been researching different solutions, but I am still unsure about how to effectively integrate Express with multiple view folders. Imagine an Express application divided into distinct parts, each organized in its own subfolder: app +partA + ...

I am attempting to utilize Ajax in order to transfer information to a different webpage

It's a bit complex and I can't figure out why it's not working. My goal is to create a page with textboxes, dropdown lists, and a datagrid using easyui. The issue arises when I select something from the dropdown list - I want two actions to ...

Rendering nested routes in Vue router with the parent component

I attempted to nest my routes using Vue router, but encountered some difficulties { path: '/admin', name: 'Admin', component: () => import('pages/Admin'), children:[ { path: 'stock', name: ' ...

Substitute the element with its outerHTML and then grab hold of the fresh element instantly

My current approach involves replacing a DOM element by updating its content with the outerHTML property. This method is effective, but my challenge lies in promptly accessing the newly generated DOM element. Regrettably, I do not have control over the cr ...

What is the best way to handle the JSONP data from the api.themoviedb.org response?

I am working with the themoviedb.org API to retrieve movie information. Below is the code I have implemented: let req = new XMLHttpRequest(); req.open("GET", "http://api.themoviedb.org/2.1/Movie.search/en/json/XXX/immortals?callback=foobar", true); req.se ...

Error: Request Timed Out - The asynchronous callback function was not executed within the specified timeout set by the jasmine.DEFAULT_TIMEOUT

Currently, I am in the process of testing my Ionic app using Jasmine. Below is a snippet from my test suite: beforeEach(() => { auth = new Authentication(<any>new HttpMock(), <any>new StorageMock()) user = new MockUser(); head ...

Finding Node.js modules with a specific field: A comprehensive guide

Inquiry: What is the method to import modules that contain the example field in their package.json? Illustrative instance: const path = require( "path" ); const glob = require( "glob" ); const modules = glob.sync( './node_modules/*' ); for ( ...

Is there a way to display a paragraph when a button is clicked?

I want my paragraph to appear when the button is clicked <button class="con-button" type="button">CLICK HERE</button> <p id="d-c" class="d-c">Thank you for reaching out to <strong&g ...

Modify the original source data of an HTML table

I have written the following code: <table class="table table-hover"> <thead> <tr> <th>Status</th> <th>MPK</th> <th>Full Name</th> <th>Phone Number</th> <th>Proj ...

Change the order of table data cells using jQuery / Javascript

Can you reverse the order of td values in a table? For example, if I add a class to the td elements I want reversed called 'valuesToFlip' $('.valuesToFlip').reverse() // Attempting to reverse but it's not working. ...

"Encountering a 500 internal server error with jQuery and WordPress

I'm having issues implementing ajax into my WordPress project to dynamically load videos based on their post ID. Whenever I click on the video link, a 500 internal server error occurs. I'm sending the post ID through ajax to a PHP script where I ...

What is the best way to set a fixed width for my HTML elements?

I am facing an issue with my user registration form where error messages are causing all elements to become wider when they fail validation. I need help in preventing this widening effect. How can I achieve that? The expansion seems to be triggered by the ...

Error: Unable to execute function abc, it is not defined as a function in this context

Having trouble with a fronted or JavaScript issue where it can't find the defined function in the file. I'm working on integrating Apple Pay and need to call the back-end API based on a specific event. Here is my code. ACC.payDirect = { _autoload ...

A guide on showcasing a MultiPolygon GeoJSON on a Leaflet map

I am attempting to showcase a GeoJSON MultiPolygon object on a Leaflet map. I retrieve it from a PostgreSQL database as JSON and transform it into GeoJSON. I have validated the MultiPolygon object on GeoJSONLint and it checks out: However, I am facing di ...

Implementing Browser Back or Back button in AngularJS

Currently, I am developing an application that utilizes route methods to navigate between webpages for different modules. Essentially, it is a single page application with route methods responsible for loading the HTML content in the body section. The iss ...

What is the best method to deactivate zoom in/out buttons using JavaScript?

As a newcomer to Phonegap, I've managed to implement zoom in/out functionality using websettings in the .java file. However, I now face a challenge where I need to disable/enable the zoom in/out buttons and stop scrolling at a specific point. I attemp ...

Maximizing Performance: Enhancing Nested For Loops in Angular with Typescript

Is there a way to optimize the iteration and comparisons in my nested loop? I'm looking to improve my logic by utilizing map, reduce, and filter to reduce the number of lines of code and loops. How can I achieve this? fill() { this.rolesPermiAdd = ...

Learn how to dynamically alter the background color of a webpage by utilizing a JSON API for random color selection

My goal is to trigger a javascript function onload that will dynamically change the background color of the webpage using random colors fetched from a JSON file. ...