0

I have an array with objects, each object, a div, has an id. Can I retrieve the array index number of a given object based on its id using this?

var index = ar.map(function(el) {
  return el. ??
}).indexOf('objectID4'); 
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
user3024007
  • 283
  • 4
  • 12

3 Answers3

2

Like this:

var index = ar.map(function(el) {
  return el.id;
}).indexOf('objectID4');

working example: http://jsfiddle.net/bvT6B/

CD..
  • 72,281
  • 25
  • 154
  • 163
0

check for below code

var ar = [{'id':'objectId1','foo':'bar'},{'id':'objectId4','foo':'bar'}]

var index = ar.map(function(el) {
   return el.id;
}).indexOf('objectId4');

alert(index);

Or you can see in http://jsfiddle.net/VJrWc/

If this is not you want the share some more code and clear your goal.

Bhavesh Parekh
  • 212
  • 2
  • 11
-1

It this what you want?

<div id="x1" class='foo'></div>
<div id="x2" class='foo'></div>
<div id="x3" class='foo'></div>

<div id="res"></div>
<script>
function getIndexOfById(uid) {
    var id = null;
    $('.foo').each(function() {
        if ($(this).attr('id') == uid) {id = $(this).index();}
    });
    return id;
}

$('#res').html(getIndexOfById('x1') + ' / ' + getIndexOfById('x2') + ' / ' + getIndexOfById('x3'));
</script>

The result is

0 / 1 / 2
BaBL86
  • 2,602
  • 1
  • 14
  • 13