A
A
Alex2016-05-31 08:48:34
JavaScript
Alex, 2016-05-31 08:48:34

What is the fastest way to search through an array of objects?

There is an array of objects of the form:

[{
    id:123,
    name: 'Name1'
},{
    id: 321,
    name: 'Name2'
}]

What is the fastest way to find an array element by a given id?
As an option, I considered converting the array into an object:
{
  123: {
    id:123,
    name: 'Name1'
  },
  321: {
    id: 321,
    name: 'Name2'
  }
}

But the problem is that in the course of the application's operation, this array is constantly changing: new elements are added and removed, as well as the properties of individual elements. And every time you change the array, you have to re-create the indexed object. So I'm looking for an alternative.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Misty Hedgehog, 2016-05-31
@Kozack

If the project uses jQuery, then I think it makes sense to refer to jQuery.grep :

var source = [{
    id:123,
    name: 'Name1'
  },{
    id: 321,
    name: 'Name2'
  }];

function getObject(source, id) {
  return jQuery.grep(source, function(e){ return e.id == id; });
}

console.log(getObject(source, 321));

If the array is not very large, then a simple enumeration will probably be quite enough:
function getObject(source, id) {
  for (var i = 0, len = source.length; i < len; i++) {
    if (source[i].id == id) {
      return source[i];
    }
  }
}

If it is possible to use ECMAScript 6, then you can refer to its native function (for "old" browsers, you can include this polyfill ):
function getObject(source, id) {
  return source.find(function (el) {
    return el.id === id;
  });
}

Or resort to the well-supported filter method :
function getObject(source, id) {
  return source.filter(function(el) {
    return el.id === id;
  })[0];
}

Which of the methods will show itself better for you - use that one. For tests, just run each one like so:
console.time('test_func_exec');
for (var i = 0; i < 10000000; i++) {
  getObject(source, 123);
}
console.timeEnd('test_func_exec');

By running each a dozen times on "combat" data, and taking the average execution time of each (testing, as I believe, you will do in the browser).
Have a nice day!

N
Nicholas, 2016-05-31
@healqq

What is the size of the array? If <1000 elements - array.filter will be enough.
If more - you can store pairs {id -> element} in the object. In fact, you will only need to add a new element to the hash or remove the deleted one from the hash.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question