Note that there are some explanatory texts on larger screens.

plurals
  1. POwhich approach is best to search object in array?
    primarykey
    data
    text
    <p>I've sorted following ways to search for an object in array. This question has been asked like countless times but I want to know which of the best from following ways. If there's another I'd like to know that too.</p> <p><strong>Using <code>$.grep()</code></strong></p> <pre><code>function is_in_array(arr,element){ var result = $.grep(arr, function(e){ return e.id == element; }); return result.length; } </code></pre> <p>Above function returns length of array.</p> <ul> <li>0 when element not present</li> <li>1 when element present</li> <li>length > 1 if more elements with same value present</li> </ul> <p><strong>using lookup object</strong></p> <pre><code>var lookup = {}; for (var i = 0, len = array.length; i &lt; len; i++) { lookup[array[i].id] = array[i]; } </code></pre> <p>This way I don't need to traverse entire array each time. I'd just check for <code>lookup[id]</code> instead.</p> <p><strong>for loop in traditional way</strong></p> <pre><code>function in_array(array, id) { for(var i=0;i&lt;array.length;i++) { if(array[i].id === id) { return true; } } return false; } </code></pre> <p>to check if element exists, i'd call <code>in_array(arr,element)</code>.</p> <p>Which approach is best ? Question seriously sounds duplicate and it is but I just want to make sure which is best from these three only.</p> <p><strong>Update</strong></p> <p>Array will contain objects like --</p> <pre><code>var arr = []; var nameObj = {}; nameObj.label = "somename"; nameObj.id = 123; arr.push(nameObj); . . . </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload