What is the best method for eliminating an element from an array when a specific key is

Essentially, the dataSource for the kendo grid has a default data called selVal. If any key from selval matches with dtoVal, I want to delete everything from selVa. Is it possible to implement this with the code below? It's not deleting selVal elements from the array. Any ideas?

ctrl.js

$scope.handleControlOwnerCancel = function(){
                this.ctrlOwnerModal.close();
                var dtoVal = $scope.controlDTO.controlOwners;
                var selVal = $scope.selectedOwners;
                for (var i = 0; i < dtoVal.length; i++) {
                  for (var j=0; j<selVal.length; j++)  {
                   if (dtoVal[i].workerKey  !== selVal[j].workerKey) {
                     $scope.selectedOwners = $scope.controlDTO.controlOwners;
                     controlOwnersDataSource();
                    }
                  }
                }

            };

Answer №1

Consider using angular.forEach instead of a traditional for loop for improved efficiency. Additionally, you mentioned:

If any key from selval matches with dtoVal, I want to remove all entries from selVa.

However, in the loop, you are checking with !==. It's unclear what exactly your requirement is. You could try this approach:

$scope.handleControlOwnerCancel = function(){
    this.ctrlOwnerModal.close();
    
    var match = 0;
    angular.forEach($scope.selectedOwners, function(val, key){
        angular.forEach($scope.controlDTO.controlOwners, function(val2, key2){
            if(val.workerKey==val2.workerKey){
                match++;
            }
        })          
    })
    if(match>0){
        $scope.selectedOwners = $scope.controlDTO.controlOwners;
        controlOwnersDataSource();
    }
};

Answer №2

Give this a shot

$scope.handleControlOwnerCancel = function(){
  this.ctrlOwnerModal.close();
  var dtoVal = $scope.controlDTO.controlOwners;
  var selVal = $scope.selectedOwners;
  var selValCopy = angular.copy(selVal);
  for (var i=dtoVal.length-1; i>=0; i--) {
    for (var j=selVal.length-1; j>=0; j--)  {
      if (dtoVal[i].workerKey  === selVal[j].workerKey) {
        selValCopy.splice(j, 1);
      } else {
        $scope.selectedOwners = $scope.controlDTO.controlOwners;
        controlOwnersDataSource();
      }
    }
  }
  selVal  = selValCopy;
};

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

Should data objects be loaded from backend API all at once or individually for each object?

Imagine having a form used to modify customer information. This form includes various input fields as well as multiple dropdown lists for fields such as country, category, and status. Each dropdown list requires data from the backend in order to populate i ...

Implement the color codes specified in the AngularJS file into the SASS file

Once the user logs in, I retrieve a color code that is stored in localstorage and use it throughout the application. However, the challenge lies in replacing this color code in the SASS file. $Primary-color:#491e6a; $Secondary-color:#e5673a; $button-color ...

Is my rtk slice's initial state not being saved correctly in the store?

Currently diving into the world of RTK with typescript. I have created 2 slices - one using RTK query to fetch data (called apiSlice.ts) and another utilizing createSlice for handling synchronous state changes in my todo app (named snackbarSlice.ts). The ...

Converting an Ajax request from JavaScript to jQuery

I am new to Ajax and trying to convert an ajax request from javascript to jquery without success. Here is the javascript code snippet I am working with: function aaa(track_id) { var req = new XMLHttpRequest(); req.open("get", "list.php?tr=" + track_id, ...

Tips for preventing a page refresh using HTML, JQuery, AJAX, and PHP

I need assistance with transferring the value of a selected radio button to a PHP session variable using Javascript/AJAX. Everything seems to be working fine, except that the page refreshes each time. Is there a way to prevent this from happening? Below i ...

What is the best way to align text in the center of a div?

I just created this dropdown menu, but I am encountering an issue. Whenever I resize the div or h4 element, the text ends up at the top. Even after trying to solve it with text-align: center;, the problem persists. Here is a visual representation of what ...

Why does the selectedItems in the AngularJS grid keep coming back as undefined?

Is there a specific reason why the angularjs grid in my sample isn't displaying the selectedItems properly? Every time I attempt to reference the selectedItems, it returns "undefined." I have tested this in both Chrome and IE with identical outcomes. ...

Creating unit tests for a state that includes PreparedQueryOptions within Jasmine framework

Currently, I am in the process of writing a Jasmine test case for the state within Angular JS. The resolve section of my state looks something along these lines: resolve: { myResult: function () { var dfd = $q.defer(); ...

Can I employ a PHP script as a "server" for a React application?

As I am using shared hosting without Node installed, I can't utilize Express as a server (or any other node-related features xD). The issue arises when fetching data from the Behance API in my app and encountering a CORS error. To address this probl ...

Mastering image focus with javascript: A comprehensive guide

On my HTML page, I have two images and a textbox. I want the focus to shift between the images based on the first character entered in the textbox. For example, when the user types '3', the first image should be focused, and for '4', th ...

Is there a way to retrieve two distinct values from an object?

Is there a way to retrieve two target values from an option using useState in react/nextjs? Here is a sample of my api: const movies = [ { id: 1, name: "Fight Club" }, { id: 2, name: "Titanic" }, { ...

Separating Angular JS controller and Factory into individual files allows for easier organization and

As someone new to web development and Angular, I recently created a module, factory, and controller all in the same file (app.js). Below is an example of the code: //Main Module var ipCharts = angular.module('ipCharts', []); //Factory ipCharts. ...

Using ng-repeat and selectize in AngularJS to populate a multi-select drop-down with values and set selected values

In this instance, I was able to achieve pure HTML select multiple functionality by using this example (JS Bin of pure html select tag). However, instead of sticking to just the pure HTML approach, I opted to use the Selectize plugin. The confusion arose w ...

Code snippets to reduce excess white space on a website using HTML and CSS

On my website, there are multiple tabs, each containing content from an HTML file. When a user clicks on Tab1, boxes with images are displayed. The layout can be seen in the following Code Demo: Code Demo here There seems to be extra space before and afte ...

Contrasting include versus block in Jade

Can you explain the distinction between blocks and include in Jade template creation? How do you determine when to use each one? ...

Having issues with executing promises within map function in JavaScript

I am currently working on a JavaScript function that handles API calls within a map method. However, before completing all the tasks within the map method, my function is producing incorrect results. It is not meeting my expectations. Here is the code sni ...

Store in database and forward to a different web address

I have created an interactive quiz using jQuery. I need to add a specific feature at the end of the quiz. if (answered_questions === total_questions) { save the user's score to the database; redirect to specified URL; } The redirect_url is ...

Utilize regular expressions in TamperMonkey to extract specific groups of text

I'm currently working on a TamperMonkey userscript that aims to identify URLs matching a specific pattern, visit these pages, extract relevant information, and then update the link for each URL with the extracted text. I'm facing some challenges ...

Update the Material UI input field value using an external JavaScript script

Imagine I find myself exploring an online form that utilizes Material UI components, for instance, this example link. I am interested in automatically filling the input fields with a specific value using JavaScript in the console: for (input of document.g ...

Using axiosjs to send FormData from a Node.js environment

I am facing an issue with making the post request correctly using Flightaware's API, which requires form data. Since Node does not support form data, I decided to import form-data from this link. Here is how my code looks like with axios. import { Fl ...