2

My array looks something like this:

var someArray = 

    [
        { id: 'someID', name: 'someName', title: 'someTitle' },
        { id: 'anotherID', name: 'anotherName', title: 'anotherTitle' },
        { id: 'otherID', name: 'otherName', title: 'otherTitle' }
    ];

I want to get index reference of an object that who's id === 'anotherID' in reference with someArray

I know that I can use $.grep() to return an object:

var resultArray = $.grep(columns, function(e){return e.id === 'anotherID'}); 

resultArray will return an array of objects that match the condition of anonymous function, but it will not return an index of that object in someArray

I am looking for JavaScript/Jquery solution. Thank you.

4
  • are you using underscore.js? They have algo for this and many more Commented Aug 2, 2013 at 20:04
  • 1
    @user814628 Question is tagged with jquery. Pay attention. Commented Aug 2, 2013 at 20:08
  • @FelixKling It may and at same time, may not. Since he is using jquery, then it's not duplicated. Commented Aug 2, 2013 at 20:18
  • 1
    @RaphaelDDL: Then you might want to close it as duplicate of this one: jQuery: Index of element in array where predicate. Commented Aug 2, 2013 at 20:21

5 Answers 5

1

A simple for:

var elementIndex = false;
for ( var index = 0, length = someArray.length; index < length; index++ ) {
    if ( someArray[index].id === 'anotherID' ) {
        elementIndex = index;
        break;
    }
}

if ( elementIndex !== false ) {
    console.log(elementIndex);
}
Sign up to request clarification or add additional context in comments.

Comments

1

The easiest way is going to be to write your own function (unless you have access to the built-in indexOf method and it works for you:

var indexOf = function(array, predicate) {
   for(var i = 0; i < array.length; i++) {
       if(predicate(array[i])) {
           return i;
       }
   } 
   return -1;
}

Which you could then call like:

var index = indexOf(someArray, function(e){ return e.id === 'anotherID'; });

Comments

1

.reduce() is not supported by IE8

One liner using reduce:

someArray.reduce(function(p,c,i){return c.id=='anotherID'?i:p},-1);

Comments

0

Using jQuery's $.each:

var posIndex = '';
$.each(someArray, function(i){
    if(someArray[i].id === 'anotherID'){
        posIndex = i;
        return false; /*Stop iterating once found. Tip from Felix Kling*/
    }
});

See example fiddle (upper code part).

As you see, using jQuery is alot easier than normal JS for.

This answer considers that each id is really an identifier (a.k.a. unique) or else posIndex will return the position of the last object which has anotherID.

Update Added 'Felix Kling' tip of return false;. Now it will return the first match only. If have more than one id with same value, use below. Thanks Felix.


If you think that might have multiple equal ids, I suggest that posIndex becomes an array and then you read the array later. Example:

var posIndexArray = [];
$.each(someOtherArray, function (i) {
    if (someOtherArray[i].id === 'anotherID') {
        posIndexArray.push(i);
    }
});

And posIndexArray will be a comma separated list of indexes you can then use $.each on it to do whatever you want with the indexes.

See example fiddle (lower code part).

5 Comments

The better answer so far, since the Q is tagged jquery AND it comes with a fiddle.
@Jeffman Thanks. I've updated answer to cover when there's more than one id with same value (non-unique id).
@RaphaelDDL Great answer! I am giving you +1 for a really nice and efficient answer. I would also give you +2 for fiddle and the second part of the answer, but I can't. Thank you
If you assume that the ID's are unique, you can return false; from the callback to avoid iterating over the remaining elements once you found a match.
@FelixKling Added your tip to the answer. That's a good one btw. Thanks +1 :)
0

You can achieve this pretty easily using either plain ol' JavaScript or jQuery if you so choose!

le vanilla

function getById(id, objects) {
  for (var i = 0, length = objects.length; i < length; i++) {
    if (objects[i].id === id) {
      return i;
    }
  }

  return -1;
}

jQueryyy

function getById(id, objects) {
  var index = -1;

  $.each(objects, function(i) {
    if (this.id === id) {
      index = i;
      return false;
    }
  });

  return index;
}

From that point, you could just call your little handy-dandy helper function and check that you got a good index.

var index = getById('otherId', someArray);

if (~index) {
  doSomethingAwesome(someArray[index]);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.