Benedict Lewis
Benedict Lewis

Reputation: 2813

Search inside array of objects

I have an array, which is formatted as such:

var clients = [{
    "id": 1, 
    "hash": 5c5fbbb047984ca8eec6dc7a3d994c09, 
    "more": {...}
  }, 
  {
    "id": 2,
    "hash": 620628ce37817a94476d55e55a543bee,
    "more": {...}
  }, 
  {...}, 
  {...}];

It contains around 25 objects, but this can change. My program gets an ID, which is an integer, and what it has to do it look in the clients array, and find the object with the specified ID, and then remove that object from the array.

What is the best, most efficient way to do this, given that there could be a relativly large number of objects?

Upvotes: 0

Views: 79

Answers (2)

thefourtheye
thefourtheye

Reputation: 239573

You can use Array.prototype.filter function, like this

var clients = [{"id": 1, "hash": "5c5fbbb047984ca8eec6dc7a3d994c09"},
               {"id": 2, "hash": "620628ce37817a94476d55e55a543bee"}];
var idToRemove = 1;

clients = clients.filter(function(currentObject) {
    return currentObject.id !== idToRemove;
});

console.log(clients);

Output

[ { id: 2, hash: '620628ce37817a94476d55e55a543bee' } ]

Upvotes: 2

Peter Olson
Peter Olson

Reputation: 142947

You can loop through the array and delete the entry with a given id.

function removeClient(clients, id) {
  for(var i = 0; i < clients.length; i++) {
    if(clients[i].id === id) {
      clients.splice(i, 1);
      return;
    }
  }
}

You can also use the Array.prototype.filter function for this, but I like this iterative solution better for two reasons:

  • It exits once the client is found and removed, instead of always going through the entire array.
  • It works on IE8 and lower, whereas Array.prototype.filter is an ECMAScript 5 feature that was not supported by IE until IE9.

Upvotes: 1

Related Questions