Check index in array of objects by property

0

When I click on an element, I get an id. With this I go into an array and find out which object has the same id, and I need to remove all objects with the same id.

 function onRemove(city) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].id === city.id){
            (remover objeto do array)
         }
     }
  }
    
asked by anonymous 10.04.2018 / 13:49

4 answers

2

You can use splice to remove an index element from an array:

array.splice(i, 1);

In the example, it removes 1 element from index i

Reference: link

EDIT: An example of comments:

  function onRemove(city) {
      var removeu = true;
      while(removeu) {
         removeu = remover(city);
      }
  }

  function remover(city) {
     for (var i = 0; i < array.length; i++) {
        if (array[i].id === city.id){
            array.splice(i, 1);
            return true;
         }
     }
     return false;
  }

EDIT 2 : A solution using Array.filter :

var novoarray = array.filter(function(a){return a.id != city.id});

Example:

var array = [ {id: 1, city: 'AAA'}, {id: 2, city: 'BBB'}, {id: 3, city: 'CCC'} ];
var city = {id: 2, city: 'BBB'};

var novoarray = array.filter(function(a){return a.id != city.id});
console.log(novoarray);
    
10.04.2018 / 14:16
1

You can use splice , and when you find an instance, you decrement -1 in i :

var array = [
   {
   "id":"1"
   },
   {
   "id":"2"
   },
   {
   "id":"1"
   },
   {
   "id":"4"
   },
   {
   "id":"1"
   },
   {
   "id":"1"
   },
   {
   "id":"1"
   }
   ];

var city = { "id":"1" };

for (var i = 0; i < array.length; i++) {
  if (array[i].id === city.id){
      array.splice(i, 1);
      i--;
   }
}
  
console.log(array);
    
10.04.2018 / 14:50
0

Hello,

You can use indexOf to identify the position where your value (city id) is.

After this, you can remove the item with splice . It tells you the position where you want to start taking the removal, and the number of items you want to remove from that (1 in your case, I believe). In addition, the return of splice is the new array with the remotions made. It would look something like this:

function onRemove(city) {
    var posicao = array.indexOf(city);
    array.splice(posicao, 1);
}

Note: browser support for indexOf is limited. Not supported in Internet Explorer 7 and 8.

Of course, if indexOf does not work very well for you, you can find the city in question the way you did (sweeping with for). However, I believe splice is useful.

    
10.04.2018 / 14:35
0

Try this way (UPDATE: I upgraded to ES5 and also to delete multiple):

function onRemove(city) {
    var citiesFound = array.filter(function (a) {
        return a.id === city.id;
    });

    citiesFound.forEach(function(c) {
        var index = array.indexOf(c);

        if (index >= 0) {
            array.splice(index, 1);
        }
    });
}
    
10.04.2018 / 14:17