-1

I'm trying to slice an array after an item in it has been used but the code is not doing that:

vm.removeItem = function() {
  for(let i = 0; i < vm.array.length; i++) {
    if(vm.array[i].item === vm.item) {
      vm.array.splice(i, 1);
      break;
    }
  }
};

Is there something I'm doing incorrectly?

Mike Cluck
  • 28,921
  • 12
  • 72
  • 85
John
  • 35
  • 4
  • 1
    Does this have to be tagged angularjs? – Crescent Fresh Jul 20 '16 at 16:49
  • @CrescentFresh, doesnt havet, but I used it anyway thinking im a newbie in Angular and JS – John Jul 20 '16 at 16:51
  • What is vm? What item are you trying to slice off? The function takes no parameters, so I can only assume either the first or last element. But if that was the case, there's no need for a for loop. – sdfsdf Jul 20 '16 at 17:02

3 Answers3

0

A dummy code is being assumed. The item to be removed is stored in item. After removeItem is invoked, its removed.

var vm = {
  array: [{
    lp: 1
  }, {
    lp: 2
  }, {
    lp: 3
  }],
  item: 2
};

vm.removeItem = function() {
  for (let i = 0; i < vm.array.length; i++) {
    if (vm.array[i].lp === vm.item) {
      vm.array.splice(i, 1);
      break;
    }
  }
};

vm.removeItem();
console.log(vm.array);
Ayan
  • 2,061
  • 1
  • 9
  • 28
  • @John Please check this code, is this what you were looking for? I tried to create a dummy code to make it workable. – Ayan Jul 20 '16 at 16:53
0

According to your existing code, it seems like your vm structure looks like that:

var vm = {
  item: 'ef',
  array: [ {item: 'ab'}, {item : 'cd'}, {item: 'ef'}, {item: 'gh'} ]
};

If you want to remove from vm.array the element whose item attribute is vm.item, you can do:

vm.array = vm.array.filter(function(e) { return e.item != vm.item; });

However, I think that your code should work as expected and do exactly the same thing. So, the problem might be somewhere else.

Arnauld
  • 5,055
  • 2
  • 13
  • 26
0

This may be a duplicate of Remove a particular element from an array in JavaScript?

Anyways, you can always do something like this:

function remove(arr, item) {
  for(var i = arr.length; i--;) {
    if(arr[i] === item) {
      arr.splice(i, 1);
    }
  }
}

And here's the usage:

// an array
var entries = [
    {name:'Tim'},
  {name:'John'}
];
// add an item to the array
var mark = {name:'Mark'};
entries.push(mark);

// you can see it's in the array now
entries.forEach(x => console.log(x.name));

// remove it from the array
remove(entries,mark );

// you can see it's not there now
entries.forEach(x => console.log(x.name));
Community
  • 1
  • 1
enSquared
  • 1
  • 1