Shuffling Numbers in an Array After Removing an Element with AngularJS

I am working with a JSON array that contains tasks:

tasks = [{taskcode:1, taskName:'abc'},
       {taskcode:2, taskName:'abc1'},
       {taskcode:3, taskName:'abc2'},
           .....
      ];

If I delete a task with the name abc, I want the task codes of other tasks to be reindexed like this:

tasks = [{taskcode:1, taskName:'abc1'},
       {taskcode:2, taskName:'abc2'},
           .....
      ];

These tasks are added dynamically by pushing values from a popup.

Can anyone help me figure out how to achieve this?

Answer №1

Instead of constantly updating the taskCode, you can rely on its position in the array to determine its value whenever needed. This way, there is no need for frequent updates. For instance, when accessing a specific object, you already know its location in the array and can simply add one to get the desired result.

In essence, your property can be represented as index + 1. If you are showcasing the task codes using an ng-repeat, this approach will suffice.

<div ng-repeat="task in tasks">
    <p>Task Code: {{$index + 1}}</p>
    <p>Task Name: {{task.taskName}}</p>
</div>

If you require enumerating these taskCodes prior to any additional operations, it is advisable to execute a single loop for efficiency. By doing so, unnecessary re-indexing of the array after each small operation can be avoided. Instead, re-indexing can occur only when absolutely necessary.

$scope.enumerateTaskCodes = function() {
    $scope.tasks.forEach(function (task, index) {
         task.taskCode = index + 1;
    };
};

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

Tips for retrieving the Solana unix_timestamp on the front-end using JavaScript

Solana Rust smart contracts have access to solana_program::clock::Clock::get()?.unix_timestamp which is seconds from epoch (midnight Jan 1st 1970 GMT) but has a significant drift from any real-world time-zone as a result of Solana's processing delays ...

Formatting AngularJS ng-repeat into individual cells

Struggling to achieve a layout like this using ng-repeat with a <table>. instrument1 instrument4 instrument7 instrument10 instrument2 instrument5 instrument8 instrument11 instrument3 instrument6 instrument9 instrument12 Presenting my code.. &l ...

When utilizing Ionic Firebase, the user profile saved in the sidemenu is stored using the Events class. However, the saved profile disappears as soon as

Hello there. I am currently working on displaying my user's information in the sidemenu, and after some research, I found that using the Events class might solve this issue. However, I have noticed that the data saved in subscribe gets destroyed whene ...

Issues with location forecasts and .getPlace() when utilizing the Google Maps loader for Place Autocomplete in Vue are causing functionality problems

After setting up a Vue 2 app using the vue cli, I noticed that when typing an address, no suggestions were populating from the dropdown. Checking the network tab, I observed the AutocompletionService.GetPredictions call triggering without any errors upon p ...

Popovers in Bootstrap 4 do not have clickable Custom Forms

I find it strange that in Bootstrap 4, only custom forms are not clickable in the Bootstrap popover. It's interesting how default forms in Bootstrap 4 work just fine. Any suggestions on how to resolve this issue? Below is my code. Thank you for you ...

Guidance on retrieving state and city information using placeid within Google Maps API with AngularJS

Is there a way to retrieve the state and city information using a place_id? I am looking to extract the state and city based on the given place_id. You can refer to this link Google_map, where I need to find out the state and city of the specified place_i ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

Experiencing difficulties when trying to upload images using multer in an Express application with Node.js

I have been using multer to successfully upload images into a folder within my project. Despite not encountering any errors while using multer, I am facing an issue where the upload is not functioning as expected in my project, although it works perfectly ...

Does Transclude eliminate tr and td elements from the content?

I'm encountering an issue with my angularjs application where the tr and td tags are mysteriously disappearing. angular.module('transcludeExample', []) .directive('pane', function() { return { restrict: 'E' ...

What is the method for accessing JSON data?

Looking for assistance on a coding issue I'm facing. I need my JavaScript code to read JSON data and grant access to a staff panel based on the information provided. Below is the sample JSON: { "User1": { "User": " ...

Refreshing the current window with the ``Window.location.reload()`` function

I have integrated a map that displays clients using markers. The map I am utilizing is Leaflet with an AngularJS directive. The issue I am facing is that when I initially access the map, it functions correctly. However, when I change routes, all the marke ...

Checking if the group of radio buttons has been selected using JQUERY

Need help with validating a group of radio buttons. If none are checked, display an error message in the span element to prompt users to select an option. The strange issue I am facing is that the validation code works only when placed below the radio butt ...

Copying a class and adding the second item in the duplicated class

I have been working with an ajax function to retrieve names from the database. The issue arises when there are multiple names returned - I split them and then attempt to clone the first class in order to display the additional names. However, this proces ...

Accessing PHP variables in JavaScript

Hi there, I am new to all this. I am trying to figure out how to use a PHP variable in JavaScript. Here is a snippet of my code (popup.php): <?php $id_user = $this->session->userdata('id'); ?> <script type="text/javascript"> ...

Creating a backup link for a video player component in NextJs

My aim is to make sure that two video player components in a NextJS application can still access and play videos even when the application is running locally using npm run dev without an internet connection. Currently, these two components.. <HoverVi ...

In Perl, locate and store word and its surrounding context in a hash table

My array structure resembles the following (with over 2000 lines of similar content): @list = ( "affaire,chose,question", "cause,chose,matière", ); I aim to achieve the following output: %te = ( affaire => "chose", "question", chose ...

Serialize an array with diverse elements

Looking at the JSON string below, my task is to serialize it and send it as a body in a POST request. { "rules": [[ { "operator": "text_field_contains", "args": [ "8", "test" ...

Combining values and eliminating duplicates from an external API: A step-by-step guide

My API provides soccer game results in this format: results:[ { Group:"A" Home: "Fc Barcelona", Away: "Fc Porto" Score: { Home: 0, Away: 0 }, { Group:"A" Home: "AC Milan", Away: "Fc Barcelona" Score: { Home: 0, Away: 1 }, { Group:"A" Home: "FC Barcelona" ...

CORS blocking Axios POST request to Heroku causing a Network Error 503

Using the MERN Stack, everything was functioning correctly until modifications were made to the UI (such as relocating code to different components and altering styles). The issue lies with a specific POST request, while other requests that utilize Axio ...

Comparing Jquery's smoothscroll feature with dynamic height implementation

Recently I launched my own website and incorporated a smoothscroll script. While everything seems to be working smoothly, I encountered an issue when trying to adjust the height of the header upon clicking on a menu item. My dilemma is as follows: It appe ...