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

    };
1

5 Answers 5

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});

    };
Sign up to request clarification or add additional context in comments.

4 Comments

It should be noted that Array.filter() is IE9+. Still a good answer, though.
Thanks @GonzaloPincheiraArancibia ! . Will accept it as soon as i can.
@GonzaloPincheiraArancibia what do i do if i want to add into array with seatid 3?
for adding into array you need using Array#push method. Example: vm.emptyseat.push({seat: 3})
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);
});

2 Comments

As far as I know, forEach is not supported on IE8 too.
Duh, thanks @Mistalis. I guess I'm used to having a shiv for that one. I've updated to use Angular's forEach().
1

A native JS approach, IE 9+

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

Array.prototype.filter()

Comments

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!");
      }
  }
};

Comments

-2

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

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.