1

Within my Angular controller I have created a method which is attached to a click handler on my scope. This click handler checks to see whether a checkbox is checked or unchecked and either pulls the associated objects out of an array or puts them back in.

My else block, where I push objects back into the array, works great. However, my if block where I attempt to splice these objects from the array does not work.

Here's the relevant code:

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 believe what is happening is that my array's length shrinks each time I splice from it, so I inevitably run into a Cannot read property 'type' of undefined error halfway through the loop. How could I go about handling removing these objects from the array without running into this issue?

4
  • 2
    Iterate backwards over the array so your indexes don't change. Commented Aug 9, 2015 at 17:02
  • @GeorgettePincin, thank you! for (var i = length - 1; i >= 0; i--) worked like a charm! If you want to toss that up as an answer I'd love to give you credit for your help. Commented Aug 9, 2015 at 17:06
  • A simple solution to this would be to use Array.prototype.filter. Commented Aug 9, 2015 at 17:10
  • No problem at all. I actually was asked this for a coding challenge during an interview once...so good for you to run into it! Commented Aug 9, 2015 at 17:11

1 Answer 1

1

You have to iterate backwards over the array so your indexes don't shift. Something like this (not tested)

vm.checkToggle = function(isChecked, value) {
  if (!isChecked) {
    var length = vm.markers.length;
    for (var i = length - 1; i >= 0; i--) {
      if (vm.markers[i].type === value) {
        vm.markers.splice(i, 1);
      }
    }
  } else {
  ...
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.