Angular, delete any item from the scope that has a matching key value

One of the challenges I am facing is removing items from an array with the same key value of skillId when a button in the repeat is clicked. Here's the code snippet I have worked on:

$scope.deleteSkill = function(skill) {  

     for (var i=0; i<$scope.pathArray.length; i++){

        if($scope.pathArray[i].skillId == skill){
            $scope.pathArray.splice(i,1);
        }
    };

};

The deletion process occurs within a repeat loop where the "skill" passed represents its skillId and is functioning as intended. My attempt involves iterating through the scope's array and eliminating any item with a matching skillId. However, upon testing my logic, it appears that only one item is removed even if there are multiple matches. Any insights or assistance would be greatly appreciated. Thank you!

Answer №1

To efficiently remove elements from an array, it's important to iterate through the array from the last index to the first. This approach takes into account the changing length of the array as elements are removed.

$scope.removeElement = function (element) {
    for (var i = $scope.itemsArray.length - 1; i >= 0; i--) {
        if ($scope.itemsArray[i].id == element) {
            $scope.itemsArray.splice(i, 1);
        }
    };
};

Answer №2

In addition to my previous comment, consider implementing a basic comparison of the opposite.

$scope.removeSkill = function(skill)
{
    var newArray = [];
    for (var j = 0; j < $scope.skillSet.length; j++)
    {
      if ($scope.skillSet[j].id != skill) newArray.push(skill) //add the skill or other array value
    }
    $scope.skillSet = newArray;
};

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

Displaying a collapsible table directly centered within the table header

I am having trouble centering my table header in the web browser page. When I click the "+" button, the data is displayed beneath the table header, but I want the collapsible table to be centered directly below the header. I have tried making changes in CS ...

Is it possible to assign a type conditionally depending on the value of a boolean?

While grappling with this issue, the title question arose in my mind: How can I handle the situation where the library function getResponse returns { a: number } for Android phones and { b: number } for iOS phones? The code snippet below initially led to ...

Prevent form submission using jQuery based on ajax response, or allow it to submit otherwise

After setting up some jQuery code to handle form submission, the functionality is working well when certain conditions are met. However, I am facing a challenge in allowing the form to be submitted if the response received does not match specific criteria. ...

Creating Tree diagrams with pie charts using D3

Has anyone tried creating a D3 pie component within each node of a tree? I've managed to build the tree and a single pie separately, but I'm struggling to combine them. My JSON data looks like this: window.json = { "health": [{ "value" ...

Discovering the exact latitude and longitude coordinates along a specific route using Google Maps

I've encountered a problem with finding the latitude and longitude along a given route using Google Maps DirectionsService. I have a JSON dataset containing latitude, longitude, and price details. My goal is to plot markers on the map and determine wh ...

Retrieve information from a local API using Next.js

While working with Next.js api today, I encountered an issue. I needed to fetch data from my internal API in getStaticProps. However, the documentation advises against fetching local API directly in getStaticProps and instead suggests importing the functio ...

Can you show me a comprehensive list of all the REST endpoints for Express mounted Apps?

When working with Express 4, you can utilize the app._router.stack object to list your app routes. In one of the routes in my todos module routes file, I attempted to display this object by sending it as part of the response: exports.update = (req,res) = ...

Sorting JSON data using JQuery Ajax

I've encountered an issue with sorting JSON data. Here is the JSON data I'm working with: [ { nom: "TERRES LATINES", numero: "0473343687", image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12 ...

Trigger callback function when user selects a date on the calendar using Material UI X Date Picker

I am currently utilizing the DateTimePicker component in material ui, version 5. I am looking for a way to intercept the callback triggered when a user clicks on a day in the calendar selector: https://i.stack.imgur.com/0Tlogm.png Although the DateTimePi ...

two occurrences of the identical controller in AngularJS

Encountering a dilemma (admittedly, not the best approach). There is a single view featuring a split screen; an input field occupies the left side while its corresponding value appears on the right. Both sides are managed by the same controller, using the ...

Locate the specific version of a JavaScript library within compiled JS files

The dist folder houses the results of running npm install. If I don't have access to the original package.json file used during the compilation of the distributable, how can I determine the version of a particular library that was utilized in the ins ...

When my script is located in the head of the HTML page, I am unable to

My goal is to make my JavaScript code function properly when I insert it into either the head or body elements of an HTML document. Let's look at some examples: First, I insert the script into the body as shown in this example (works correctly): ...

Executing a group query for Mongoose in a node.js/express route

Hey there, I have a query that works perfectly fine in Robomongo. Here's the code: db.av.group( { key: { roomId: 1}, cond: { dateOfDay: { $gte: new Date('12/01/2014'), $lt: new Date('12/30/2014') } }, reduce: function( curr, re ...

AngularJS blank drop-down selection

I am currently working on an AngularJS select element with ng-options using the code below: <select ng-model="vm.selectedship" ng-change="vm.updateShip()" data-ng-options="ship as ('ship' + ' is ready (' + ship.currentlocation + & ...

Ways to align div elements

I am currently in the process of developing my own custom animation player. Utilizing Three.js for object rendering has been successful so far. However, the challenge lies in incorporating control options at the bottom of the player interface (such as play ...

Reactjs throwing an Unsupported Media Type error with code 415

I am currently working on implementing a delete function to remove banner images. Here is the code snippet for my delete function: const [del, setDel] = useState([]); const DeleteBanner = async (banner) => { setDel(banner); ...

transfer the value of a method to a different component

In my Component called IncomeList, there is a method named sumValue. This method simply adds different numbers together to produce one value, for example 3+5 = 8. Similarly, in another Component named OutputList, the same logic is applied but with a method ...

Error: The property 'length' cannot be read from an undefined parent causing Uncaught TypeError

Hey there, take a look at this cool stuff http://jsfiddle.net/J9Tza/ <form class="validation"> <div> <input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email" pattern=".{3,200}" title="3 to 200 characters" r ...

Incorporating a Script into Your NextJS Project using Typescript

I've been trying to insert a script from GameChanger () and they provided me with this code: <!-- Place this div wherever you want the widget to be displayed --> <div id="gc-scoreboard-widget-umpl"></div> <!-- Insert th ...