I am facing an issue with my ng-model where it is accepting duplicates even though that is not my intention

I'm currently working on a dropdown menu that allows multiple selections, utilizing ng-model, ng-options, and ng-change clauses. However, I've encountered an issue where duplicate objects are being pushed into the model. To solve this problem, I attempted creating a second temporary array to filter out duplicates but was unsuccessful in implementing it. Let me elaborate with some code snippets.

Here are examples of objects being added to the select object:

[{
userProfileID: "3f8c553c-3633-4fe9-a007-4346a783450c",
firstName: 'Austin',
lastName: 'Hunter',
email: 'ahunteroutlook.com',
password: 'admin',
companyProfileID: "86660a5b-7f61-4238-889d-1cc3087947b9",
accessLevel: 'admin'
},
{
userProfileID: "bc579485-95a7-4e8d-bdde-52272923576e",
firstName: 'Ashley',
lastName: 'Jeanette',
email: 'ashleygmail.com',
password: 'admin',
companyProfileID: "86660a5b-7f61-4238-889d-1cc3087947b9",
accessLevel: ''
}]

My ng-change function logic goes like this:

$scope.changedDepartment = function(item) {
    $scope.selectUser = [];
$scope.users = [];
$scope.tempUsers.length = 0;
  if ($scope.department.length > 0) {
    if (item[0].DepartmentUsers.length > 0) {
    $scope.users.length = 0;
    for (var i = 0; i < item.length; i++) {
     for (var j = 0; j < item[i].DepartmentUsers.length; j++) {
       if (profile[0].userProfileID != item[i].DepartmentUsers[j].userProfileID) {
                $scope.tempUsers.push(item[i].DepartmentUsers[j]);
       }
     }
    }

(apologies for the formatting, had to copy-paste from code which messed up the indentation)

In summary, the function detects a selection in the dropdown, retrieves the associated users within that selection, and adds them to $scope.tempUsers. The ultimate goal is to have these users stored in $scope.users. My challenge lies in removing any duplicates from $scope.tempUsers, a task that I am struggling with. Any assistance or advice on how to achieve this would be greatly appreciated.

Answer №1

After implementing this technique, I successfully resolved the issue:

for (var x = 0; x < $scope.tempCustomers.length; x++) {
    for (var y = x + 1; y < $scope.tempCustomers.length; y++) {
        if ($scope.tempCustomers[x].customerID == $scope.tempCustomers[y].customerID) {
            $scope.tempCustomers.splice(y, 1);
        }
    }
    $scope.customers.push($scope.tempCustomers[x]);
}

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

How can I define boundaries for objects in Three.js?

How can I customize the border width and color of a polygon/polyhedron created with three.js? The example code below shows a figure, but I'm unsure how to set borders. Are there alternative methods for creating polygons? <html> <head> ...

Tips for including MIME type in headers

Everything was running smoothly with my C# web application. However, to enhance security measures, I decided to add the "nosniff" custom header in the web.config file. <system.webServer> </handlers> <httpProtocol> &l ...

Monitor changes in Angular Reactive forms to retrieve the field name, as well as the previous value and the current value of the field

this.formData = this.fb.group({ field1: '', field2: '' }); this.formData.valueChanges.pipe(startWith(null), pairwise()) .subscribe(([previous, current]: [any, any]) => { console.log('PREVIOUS', previous); co ...

Tips for creating a stylish scrollbar in a React Material-Table interface

Currently, I am utilizing the react material-table and looking to implement a more visually appealing scroll-bar instead of the default Pagination option. Although I have experimented with the react-custom-scroll package, it has not produced the desired ...

Working with color fills in Three.js shapes

Looking for some help with code that generates a yellow circle: let radius = 5, segments = 64, material = new THREE.LineBasicMaterial( { color: 0xF0C400 } ), geometry = new THREE.CircleGeometry( radius, segments ); geometry.vertices.shift ...

Ways to ensure the final unchecked checkbox stays in the checked state

I currently have a set of checkboxes that are pre-selected. However, I would like to ensure that if all checkboxes except one are unchecked, and an attempt is made to uncheck that final checked checkbox, an error message will appear and the checkbox will n ...

RethinkDB is throwing a ReferenceError because the connection variable has not been defined

Utilizing Express.js and Rethink, I am attempting to execute a straightforward post to a route that saves data to the database. The initial connection is successful and logs the message Connected to Rethink, but when I try to use the connection to insert ...

Treat characters in Javascript as visual representations and interact with them accordingly

Currently, I am expanding my knowledge of JavaScript and would like to experiment with a new idea: On one of my web pages, there is an element: <div class="movingWord">Screwdriver</div> My goal is to apply a function when hovering ...

Experimenting with Extjs compatibility using Selenium

I am currently in the process of testing an extjs application using Selenium. I am utilizing Selenium IDE for Firefox and Javascript with Eclipse on Chrome. Despite spending countless hours searching for a solution to my problem, I have been unable to iden ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...

Express.js post method malfunctioning for BMI calculation

Currently, I am working on a BMI calculator application in JavaScript as part of my practice. The app is supposed to take two inputs - weight and height, calculate the BMI, and display the result on the web page. However, after inputting the data and submi ...

Exploring nested arrays of objects and applying value constraints

Is there a way to iterate through an array and display only 5 items at once, with the option to call a function on click that will add another 20 items? I have an object structured like this: let someObject = [ { data: [ { id: 123, ...

Utilizing Mongoose.js to nest a find() query within another find() query

Can I perform a nested search on Node using Mongoose? I need to update a user's email address, but first I have to ensure that the new email is not already associated with another user. This is what I want to achieve: /***************************** ...

Is it possible to create a translucent glass floating box over HTML elements, similar to the frosted glass effect seen in iOS7?

Creating an overlapping div with a frosted glass effect typically requires using an image background (like ). I am interested in having a floating div (position:fixed) that can apply a frosted glass effect over any content below it, whether it be an image ...

Can a standalone Angular plugin be developed for seamless integration within different Angular websites?

My affinity for Angular runs deep. That being said, I have a desire to develop an Angular plugin that can be seamlessly integrated into websites using various frameworks. Whether it's Angular or something different, my goal is compatibility across th ...

When do jQuery.when callbacks trigger when every Deferred is no longer 'unresolved' (resolved or rejected)?

When you pass multiple Deferred objects to jQuery.when, a new "master" Deferred object is returned. This master Deferred object keeps track of the overall state of all the Deferreds it received. Here's how the method works: The master Deferred reso ...

CSRF validation did not pass. The request has been cancelled. The failure occurred due to either a missing or incorrect CSRF token

Upon hitting the submit button in the login form, I encountered the following error message: Forbidden (403) CSRF verification failed. Request aborted. CSRF token missing or incorrect. settings.py MIDDLEWARE = [ 'django.middleware.security.Secur ...

Can one open a unique custom pop-up before the window is about to close?

Seeking a way to create a pop-up confirmation dialog for users when they try to log out or stay on the page while logged in. I attempted using the code below, but haven't been able to find the correct solution: window.onbeforeunload = function (e) { ...

Using the Context API dispatch (consumer) within the _app.js class component in Next.js

How can I access the dispatch Context API methods in the _app.js file? The issue I am facing is that I am using React hooks along with Context API, and as _app.js is a Class component, I cannot directly use hooks within it. Below is my current code snipp ...

While trying to set up a development server in Firebase, I mistakenly deleted my build folder

I recently encountered an issue with my Firebase project. While trying to set up a development server for my existing React web app that is already in production, I ran into some unexpected problems. firebase use bizzy-book-dev firebase init firebase ...