What is the fastest way to search in 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 search for elements of the array for a given id?
Considered as a variant to translate the array into an object:
{
 123: {
id:123,
 name: 'Name1'
},
 321: {
 id: 321,
 name: 'Name2'
}
}

But the problem is that in the process of the application, this array is constantly changing: to add and delete new elements, as well as the properties of the individual elements. And every time when you change the array to re-create the indexed object. So looking for an alternative.
July 9th 19 at 10:25
2 answers
July 9th 19 at 10:27
Solution
If the project uses jQuery, I think it makes sense to turn 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, a brute-force might be sufficient:
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, you can access native functions (for "old" browsers can connect polyfil):
function getObject(source, id) {
 return source.find(function (el) {
 return el.id === id;
});
}

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


Which method will show you will show yourself better than you have - and use. For testing just run each, like so:
console.time('test_func_exec');
for (var i = 0; i < 10000000; i++) {
 getObject ('source', 123);
}
console.timeEnd('test_func_exec');

Running every ten times "battle" of the data, and taking the average runtime of each (testing, I believe you will produce in the browser).
Have a good day!
July 9th 19 at 10:29
What about the size of the array in question? If <1000 elements array.filter would be sufficient.
If more - you can store pairs of {id -> element} object. In fact you will only need to add a new item to the hash or to remove from the hash remote.

Find more questions by tags AngularGoogle ChromeJavaScript