2

How can I make the playerinit remove the seat used from emptyseats? lets say seatid is 1, then it will remove seat: 1 from emptyseats?

   vm.emptyseats = [
      {seat: 1},
      {seat: 2},
      {seat: 3},
      {seat: 4},
      {seat: 5},
      {seat: 6},
      {seat: 7},
      {seat: 8},
      {seat: 9},
    ];


    vm.playerinit = function(x) {
      console.log("init user data");
      var seatid = x.position;

      // vm.emptyseats remove where seat: seatid

    };
kukkuz
  • 37,972
  • 6
  • 47
  • 83
maria
  • 881
  • 4
  • 17
  • 46
  • 1
    Possible duplicate of [Remove item from array by value](http://stackoverflow.com/questions/3954438/remove-item-from-array-by-value) – Sebastian Sebald Oct 24 '16 at 14:51

5 Answers5

2

Using native Array#filter function:

vm.playerinit = function(x) {
      console.log("init user data");
      var seatid = x.position;

      // vm.emptyseats remove where seat: seatid
      //Using ES6 arrow function syntax
      vm.emptyseats = vm.emptyseats.filter( (empty_seat) => empty_seat.seat !== seatid);
      //Or regular syntax
      vm.emptyseats = vm.emptyseats.filter( function(empty_seat) {     return empty_seat.seat !== seatid});

    };
  • It should be noted that [`Array.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#AutoCompatibilityTable) is IE9+. Still a good answer, though. – Sam Oct 24 '16 at 14:50
  • Thanks @GonzaloPincheiraArancibia ! . Will accept it as soon as i can. – maria Oct 24 '16 at 14:52
  • @GonzaloPincheiraArancibia what do i do if i want to add into array with seatid 3? – maria Oct 24 '16 at 15:27
  • for adding into array you need using `Array#push` method. Example: `vm.emptyseat.push({seat: 3})` – Gonzalo Pincheira Arancibia Oct 24 '16 at 15:30
1

First, you need to find the index of the array you want to remove. Then, use Array.splice():

var seatid = x.position;
angular.forEach(vm.emptyseats, function(emptyseat, i) {
    if(emptyseat.seat !== seatid) return;
    vm.emptyseats.splice(i, 1);
});
Sam
  • 18,756
  • 2
  • 40
  • 65
1

A native JS approach, IE 9+

vm.emptyseats = vm.emptyseats.filter(function(a) { return a.seat != seatid; });

Array.prototype.filter()

Bogus Hawtsauce
  • 156
  • 1
  • 4
0

You can remove it with a simple for loop:

for(var i = 0; i < emptyseats.length; i++) {
    if(vm.emptyseats[i].seat == seatid) vm.emptyseats.splice(i, 1);
}

With your full code:

vm.playerinit = function(x) {
  console.log("init user data");
  var seatid = x.position;

  // vm.emptyseats remove where seat: seatid
  for(var i = 0; i < emptyseats.length; i++) {
      if(vm.emptyseats[i].seat == seatid) {
          vm.emptyseats.splice(i, 1);
          console.log(seatid + " removed!");
      }
  }
};
Mistalis
  • 16,351
  • 13
  • 68
  • 91
-2

Try using .splice() to do this. vm.emptyseats.splice(0,1);

Austin Hunter
  • 398
  • 6
  • 22