How can we eliminate every item of a specific type from an array?

On my Angular controller, I've set up a method linked to a click handler in the scope. This function checks if a checkbox is checked or unchecked and toggles the associated objects in an array accordingly.

The code block where I push objects back into the array with the else statement works perfectly. However, the if block where I attempt to use splice to remove objects from the array does not work as expected.

Take a look at the relevant code below:

vm.checkToggle = function(isChecked, value) {
  if (!isChecked) {
    var length = vm.markers.length;
    for (var i = 0; i < length; i++) {
      if (vm.markers[i].type === value) {
        vm.markers.splice(i, 1);
      }
    }
  } else {
  ...
};

I'm facing an issue where the array length decreases each time I perform a splice operation, resulting in a 'Cannot read property 'type' of undefined' error midway through the loop. How can I handle removing these objects from the array without encountering this problem?

Answer №1

To prevent the shift of indexes, you need to iterate backwards through the array. Here is an example code snippet (not verified)

vm.checkToggle = function(isChecked, value) {
  if (!isChecked) {
    var len = vm.items.length;
    for (var j = len - 1; j >= 0; j--) {
      if (vm.items[j].type === value) {
        vm.items.splice(j, 1);
      }
    }
  } else {
  ...
};

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

The Ajax operation does not finish before the second one is initiated

My Ajax function is set up like this: function PersonAtlLawUpdate(personRef) { var selectionPanel = $('div#SelectionPanel'); var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue; var timeSpan = selectionPanel.fin ...

What is the reason behind this code's ability to detect vowels as well as other

I'm currently working on debugging a specific portion of code for my class. I'm having trouble understanding why this JavaScript code is counting all letters instead of just vowels. var text, i, sLength, myChar; var count; var text = prompt("Ple ...

Troubleshooting issues with Three.js and .obj file shadows

I've been diving into learning Thee.js, and while it's fairly straightforward, I've hit a roadblock with getting shadows to work. Despite setting castShadows, recieveShadows, and shadowMapEnabled to true in the appropriate places, shadows ar ...

Exploring the possibilities of integrating React Suspense with react-router-dom

I've been exploring lazy loading in my projects to implement lazy loading routes with react-router-dom. I came across two methods while researching online - wrapping all routes with a single React.Suspense or putting each page within its own React.Sus ...

What is the best way to remove the left margin from a MuiTreeItem-group?

I'm working with the MUI tree component and I want to remove the left margin of the second layer of MuiTreeItem-group I attempted to use makeStyles to address this issue, but it didn't have the desired effect const useStyles = makeStyles(() => ...

Uploading Files Using Ajax to a PHP Class

Having some trouble with my file upload using AJAX to post to an object-oriented PHP class. Here's the AJAX code: var handleUpload = function(event) { event.preventDefault(); event.stopPropagation(); var fileInput = document.getElement ...

How to automatically select the first item in a populated dropdown list using Vue JS

My HTML select element is populated with options from a server, but when using v-model, it initially selects an empty option instead of the first one. I came across a solution on a post which suggests selecting the first option manually, but since the dat ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

Changing column sorting type dynamically with a button click using jQuery and DataTables

In the column, I have data arranged as "firstValue secondValue". It is essential for this data to remain in a single column and not split into two separate columns. When sorting is applied, it currently sorts based on both firstValue and secondValue. How ...

"After executing a loop in JavaScript using jquery.ajax, the success function does not perform

Having trouble passing values from a PHP file to another function in Javascript. Even after a successful FOR LOOP, nothing seems to work within the SUCCESS block. Any suggestions? url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php'; $ ...

Leveraging node modules in the browser using browserify - Error: fileType is not recognized

I am currently attempting to utilize the file-type npm package directly in my browser. Despite my efforts, I have encountered an error when trying to run the example code: Uncaught ReferenceError: fileType is not defined (Example code can be found here: ...

Using Node.js, Express, and Socket.IO to establish real-time communication between two static client pages

I'm in the process of creating a remote control for a gallery using nodejs, express, and socket.io. Here's the project structure: /index.js /public/screen.html /screen.js /remote.html /remote.js The goal is to display a gallery of ima ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

Ways to permit https://* within a content security policy (CSP) configuration

I'm currently incorporating CSP into my website but encountering an issue with the img-src header. I'm using NodeJS and Express to develop the site for my Discord Bot, and I want to revamp it but I've hit a roadblock. ====== This is the co ...

The tabbing feature in bxslider disrupts the alignment of slides, making it

After encountering accessibility issues, I upgraded the bxslider library to version 4.2.3 for better support. Check out this example of bxslider where you can easily tab through the controls: http://jsfiddle.net/qax7w8vt/2/embedded/result/ The problem a ...

Preventing the use of zero as the first character in the text input field

Utilizing AngularJS and jQuery along with Javascript, I have encountered an issue. While the code works perfectly in JSFiddle, it fails to function on a JSP page. $('input#myId').keypress(function(e){ if (this.value.length == 0 &am ...

Removing chips in Material UI can be easily accomplished by following these steps

Recently, I implemented a feature where chips are generated as the user types in a text field and clicks on create. A chip is then displayed with the entered text. Now, I am looking to add the ability to delete these chips dynamically. You can view the s ...

Error in Node.js: Unable to access properties of null value within Express

While using Express (with node.js) and MongoDB, I encountered an error when trying to view or update a user profile. The middleware token check worked fine getProfileFields:::::::::::::>>>>e: TypeError: Cannot read properties of null (rea ...

Uninstall webpack-dev-server version 1.14.1 and replace it with version 1.14.0

Can someone help me with the process of uninstalling webpack-dev-server 1.14.1 and installing version 1.14.0 on Ubuntu using just commands? Error message: Uncaught TypeError: Cannot read property 'replace' of null at eval (eval at globalEval (jq ...

What is the best way to implement data validation for various input fields using JavaScript with a single function?

Users can input 5 numbers into a form, each with the same ID but a different name. I want to validate each input and change the background color based on the number entered - red for 0-5, green for 6-10. I wrote code to change the color for one input box, ...