Tips for deleting a row from a JavaScript list

Plunker

I have a list from which I want to remove a row. The initial code is as follows:

var newArray = _.filter($scope.componentList, function(arrayItem) {
return rowId !== arrayItem.rowId;
});
$scope.componentList = newArray;

This filter function will keep the objects for which the return value is true and remove those for which it is false. Now, I want the same logic to be applied for both parent and child elements.

In this function, rowId acts as the input parameter. In the line $scope.componentList = newArray;, only the objects with matching rowId values are retained in the list.

return rowId !== arrayItem.rowId; 

The above line ensures that only the objects satisfying the condition are kept in the new array.

But now the format of the data has changed. It looks like this:

[
  {
    "revision": 0,  
    "componentName": "abc",
    ...
    ...
    "actionToPerform": "1"
  },
  ...
]

The relationship between parent and child rows is established using the items[] array. An attempt was made to modify the code accordingly, but it did not work as expected.

Method call:-

var newArray = $scope.isRowIdExist($scope.componentList,rowId);

Method Definition:

$scope.isRowIdExist = function(list,rowId) {

        var newArray = _.filter(list, function(arrayItem) {
            if(rowId != arrayItem.rowId){
                if (arrayItem.items && arrayItem.items.length > 0){
                    $scope.isRowIdExist(arrayItem.items,rowId); // recursive method call
                }
            }
            return rowId !== arrayItem.rowId;
        });

    }

Answer №1

Give this a try, the target element will be replaced with "REMOVED", remember to remove it from the splice function before production

angular.module("myApp", [])
  .controller("ctrl", function($scope){
    
    $scope.data = JSON.parse('[{"revision":0,"componentName":"abc","componentIdentification":"abc","componentType":"1","componentState":"1","componentUrl":null,"componentId":"214","rowId":"3","items":[{"revision":0,"componentName":"efg","componentIdentification":"efg","componentType":"2","componentState":"1","componentUrl":null,"componentId":"215","rowId":"3.1","items":null,"componentStateId":0,"ctastatus":0,"actionId":"16","actionToPerform":"1"}],"componentStateId":0,"ctastatus":0,"actionId":"37","actionToPerform":"1"},{"revision":0,"componentName":"hij"... // data continues

    $scope.toDel = "1.1"
    $scope.removeElement = function (data, toDel, parent) {
      data.forEach(function(row, i) {
        if (row.rowId == toDel) {
          if (parent) {
            parent.items.splice(i, 1, "REMOVED")
          } else {
            data.splice(i, 1, "REMOVED")
          }
        } else if (row.items) {
          $scope.removeElement(row.items, toDel, row)
        }
      })
    }
    
    $scope.removeElement($scope.data, $scope.toDel, null);
  
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
  <pre>{{data | json}}</pre>
</div>

Answer №2

My suggestion would be to avoid filtering in this scenario. The following code is effective for removing either a parent or a child:

function eliminateRow(elements, rowId) {
    for (var i=0; i<elements.length; i++) {
        var element = elements[i];
        if (rowId == element.rowId) {
            elements.splice(i, 1);
        } else if (rowId.startsWith(element.rowId)) {
            eliminateRow(element.items, rowId);
        }
        if (element.items != null && element.items.length == 0) element.items = null;
    }
}

var items = [
  {
    "revision": 0,
    "componentName": "abc",
    "componentIdentification": "abc",
    "componentType": "1",
    "componentState": "1",
    "componentUrl": null,
    "componentId": "214",
    "rowId": "3",
    "items": [
      {
        "revision": 0,
        "componentName": "efg",
        "componentIdentification": "efg",
        "componentType": "2",
        "componentState": "1",
        "componentUrl": null,
        "componentId": "215",
        "rowId": "3.1",
        "items": null,
        "componentStateId": 0,
        "ctastatus": 0,
        "actionId": "16",
        "actionToPerform": "1"
      }
    ],
    "componentStateId": 0,
    "ctastatus": 0,
    "actionId": "37",
    "actionToPerform": "1"
  },
  ...
];

/*
Psuedocode:
Conduct a rapid recursive search for |item.rowId|=|rowId| and remove the matching one
*/

function eliminateRow(items, rowId) {
for (var i=0; i<items.length; i++) {
var item = items[i];
if (rowId == item.rowId) {
      items.splice(i, 1);
    } else if (rowId.startsWith(item.rowId)) {
eliminateRow(item.items, rowId);
}
    if (item.items != null && item.items.length == 0) item.items = null;
}
}

eliminateRow(items, "1.1.1.1");
console.log(items);

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

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

Ways to show dynamic text according to slider adjustments

I am struggling with adding an if condition to my form that includes a horizontal slider. My goal is to display text based on the position of the slider. Can someone offer some guidance on this, please? Here's my HTML code snippet: <form method=" ...

What sets this.prototype apart from module.exports?

As a newcomer to the world of Node.js, I am eager to gather information, experiment with testing techniques, and explore the code written by others. In my exploration, I have noticed that creating and requiring modules is a common practice in Node.js. Dif ...

What steps should I take to design and implement this basic search form?

Essentially, I have a three-page setup: - One page containing all possible search results such as: 'search result 1' 'search result 2' 'search result 3' - Another page with a search form and enter button. - And finally, a res ...

Unable to upload gathered email to Mailchimp mailing list through Nodejs and express API

Seeking guidance on integrating data collection with Mailchimp in a Nodejs backend project. I am currently working on an email signup list page where users input their first name, last name, and email. The HTML file contains fields named firstName, lastN ...

How can I create a Discord bot command that ignores case sensitivity?

I wrote a custom "roleinfo" command for my Discord bot, but I'm struggling to make the role search case insensitive. Here is the code snippet: const Discord = require("discord.js"); module.exports.run = async (bot, message, args) => { //Me ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

How to manage form submissions in Vue.js using inputs within child components

I'm working on a parent component that acts as a form. This form consists of multiple child components, each containing input fields. <template> <div class="form"> <generalData v-model="input" /> <textAreas v- ...

When the enter key is pressed in a contenteditable div, line breaks are disregarded

Is there a way to ensure that when the return key is pressed to start a new line for a post, the output actually starts on a new line? I've been having trouble with this and would like to know the most common solution. Check out the demo below for te ...

Error occurs when a class contains a static member with the name `name`

Within my TypeScript code, I have a simple class named Foo as part of the Test module. module Test { "use strict"; class Foo { public static name = "foo"; } } However, when I attempt to run this code in Chrome, an error occurs: I ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Loading a series of images in advance using jQuery

I have a series of frames in an animation, with file names like: frame-1.jpg, frame-2.jpg, and I have a total of 400 images. My goal is to preload all 400 images before the animation begins. Usually, when preloading images, I use the following method: v ...

difficulty receiving the information promptly via an AJAX request (utilizing AJAX and the 'for' loop)

Currently, I am successfully retrieving data from an ajax call for individuals. However, my next task is to retrieve multiple sets of data simultaneously. Here is the code snippet: for(var i = 1; i <= 2; i++){ console.log(i); $.ajax({ url: cal ...

Enhance your webpage with dynamic styling using third-party CSS animation

Apologies for any similarity to other questions on this topic. I have searched extensively, but any assistance would be greatly appreciated. I am utilizing a new animation library from Animista to animate specific elements on a test website. Animating ele ...

Passing onClick event to parent component during iteration in ReactJS

I am facing a challenge where I need to remove a row from a table upon a click event. I have managed to create an iteration and display a delete button, but I am struggling with passing the onClick event from the parent component to the child component in ...

Does the onChange event fire when the value is modified by the parent element?

let [number, set_number] = useState({x: 1}); <ChildComponent number={number} onUpdate={onUpdateFunction} </ChildComponent> set_number({x: 2}) After running set_number({x: 2}), will this action prompt the execution of onUpdateFunction refere ...

Clicking on the image does not result in a larger image being displayed

Currently working on an assignment that requires a modal pop-out to display larger versions of photos when clicked, with the option to go back using the X button. Unfortunately, I'm facing issues with the X button not functioning properly and images n ...

Issue concerning the relative path of RequireJS optimizer

Currently, I am attempting to implement the require optimizer's browser example. My folder structure is set up as follows, with the "r.js" and "build.html" files located at the same level as the "js" folder. js lib | a.js | b.js | ...

Encountering the "Cannot Retrieve" error in express.js while navigating to the ID of an object

I'm in the process of developing a blog web app that allows users to create articles. Once a user clicks on 'new article', they will be taken to a page with a 'post article' button. This button triggers a post request linked to my ...

Angular = encountering an incorrect array size limitation

I am encountering an issue with the function in my controller... $scope.pagerPages = function (n) { var i = Math.ceil(n); return new Array(i); } The n value is derived from an expression on the view and can sometimes be a fraction. This is why I ...