views:

41

answers:

4

I have an array of objects. Each object has, among others, an ID attribute. I want to find the index in the array of the object with a specific ID. Is there any elegant and simple way to do this in jQuery?

+1  A: 

Not really elegant, but a cute trick:

var index = parseInt(
  $.map(array, function(i, o) { return o.id === target ? i : ''; }).join('')
);

jQuery doesn't have a lot of functional constructs like that; the philosophy of the library is really focused on the job of DOM wrangling. They won't even add a .reduce() function because nobody can think of a reason it'd be useful to the core functionality.

The Underscore.js library has a lot of such facilities, and it "plays nice" with jQuery.

Pointy
A: 

In the case you should use for loop in javascript instead of using jQuery. See way 3 in http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

UPDATED: jQuery is written in javascript and it can not be more quickly as another code written also in javascript. jQuery is very good if you work with DOM, but help you not really if you work with simple javascript arrays or objects.

The code which you are looking for can be something like following

for (var i=0, l = ar.length; i<l; i++) {
    if (ar[i].ID === specificID) {
        // i is the index. You can use it here directly or make a break
        // and use i after the loop (variables in javascript declared
        // in a block can be used anywhere in the same function)
        break;
    }
}
if (i<l) {
    // i is the index
}

Important that you should hold some simple javascript rules: declare always local variables (donn't forget var before variable declaration) and cache any properties or indexes which you use more as one time in a local variable (like ar.length above). (See for example http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices)

Oleg
A: 

See Array.filter to filter an array with a callback function. Each object in the array will be passed to the callback function one by one. The callback function must return true if the value is to be included, or false if not.

var matchingIDs = objects.filter(function(o) {
    return o.ID == searchTerm;
});

All objects having the ID as searchTerm will be returned as an array to matchingIDs. Get the matching element from the first index (assuming ID is unique and there's only gonna be one)

matchingIDs[0];
Anurag
A: 

Use jOrder. http://github.com/danstocker/jorder

Feed your array into a jOrder table, and add an index on the 'ID' field.

var table = jOrder(data)
    .index('id', ['ID']);

Then, get the array index of an element by:

var arrayidx = table.index('id').lookup([{ ID: MyID }]);

If you want the entire row, then:

var filtered = table.where([{ ID: MyID }]);

Voila.

Dan Stocker