indexOf method in an object array?

javascript indexof array of objects
javascript find index of object in array
angularjs find index of object in array by id
find index of object in array angular 2
findindex is not a function
find object in array javascript
array splice
index of object in array java

What's the best method to get the index of an array which contains objects?

Imagine this scenario:

var hello = {
    hello: 'world',
    foo: 'bar'
};
var qaz = {
    hello: 'stevie',
    foo: 'baz'
}

var myArray = [];
myArray.push(hello,qaz);

Now I would like to have the indexOf the object which hello property is 'stevie' which, in this example, would be 1.

I'm pretty newbie with JavaScript and I don't know if there is a simple method or if I should build my own function to do that.

I think you can solve it in one line using the map function:

pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');

The findIndex() method returns the index of the first element in the array that satisfies thisArg Optional: Optional object to use as this when executing callback . The findIndex() method returns an index in the array, if an element in the array satisfies the provided testing function. Otherwise -1 is returned. Just a note it is not supported on Internet Explorer, Opera and Safari, but you can use a Polyfill provided in the link below.

Array.prototype.findIndex is supported in all browsers other than IE (non-edge). But the polyfill provided is nice.

var indexOfStevie = myArray.findIndex(i => i.hello === "stevie");

The solution with map is okay. But you are iterating over the entire array every search. That is only the worst case for findIndex which stops iterating once a match is found.


There's not really a concise way (when devs had to worry about IE8), but here's a common solution:

var searchTerm = "stevie",
    index = -1;
for(var i = 0, len = myArray.length; i < len; i++) {
    if (myArray[i].hello === searchTerm) {
        index = i;
        break;
    }
}

or as a function:

function arrayObjectIndexOf(myArray, searchTerm, property) {
    for(var i = 0, len = myArray.length; i < len; i++) {
        if (myArray[i][property] === searchTerm) return i;
    }
    return -1;
}
arrayObjectIndexOf(arr, "stevie", "hello"); // 1

Just some notes:

  1. Don't use for...in loops on arrays
  2. Be sure to break out of the loop or return out of the function once you've found your "needle"
  3. Be careful with object equality

For example,

var a = {obj: 0};
var b = [a];
b.indexOf({obj: 0}); // -1 not found

More "Try it Yourself" examples below. Definition and Usage. The indexOf() method searches the array for the specified item, and returns its position. The search  IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array. IndexOf(Array, Object, Int32, Int32)

In ES2015, this is pretty easy:

myArray.map(x => x.hello).indexOf('stevie')

or, probably with better performance for larger arrays:

myArray.findIndex(x => x.hello === 'stevie')

Using indexOf would have been feasible had your array only just gets the first index, if you want the value of an element try the find method. indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator). Note: For the String method, see String.prototype.indexOf() .

var idx = myArray.reduce( function( cur, val, index ){

    if( val.hello === "stevie" && cur === -1 ) {
        return index;
    }
    return cur;

}, -1 );

To find the position of an element in an array, you use the indexOf() method. Assuming that you have the following array of objects, where each object has two​  2 Answers. indexOf just gets the first index, if you want the value of an element try the find method. Using indexOf would have been feasible had your array only contained primitive types such as numbers, strings etc. but as your array contains objects, it needs a different approach.

I like Pablo's answer, but Array#indexOf and Array#map don't work on all browsers. Underscore will use native code if it's available, but has fallbacks as well. Plus it has the pluck method for doing exactly what Pablo's anonymous map method does.

var idx = _.chain(myArray).pluck("hello").indexOf("Stevie").value();

IndexOf(Array, Object, Int32, Int32), to determine the first occurrence of the string "​the" in a string array from the element that follows the last successful match to the​  The IndexOf () method of array class in C# searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.

An overview of how the indexOf() method works to find the position of a deepIndexOf = function (target) { // If the target is an object, array or a  We first converted array to List using the asList method of Arrays class. This method returns the List wrapper of the existing array. Since List has an indexOf method, we can use it to find an element index. Please note that this code does not work for arrays of primitive types like int, float, char, double, etc.

The IndexOf() method of array class in C# searches for the specified object and returns the index of the first occurrence within the entire  The indexOf() method searches the array for the specified item, and returns its position. The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array. Returns -1 if the item is not found.

The  indexOf()  method returns the index of the first occurrence of the element in the array. It returns  -1, the elements does not exist in given array. Note that, the  indexOf()  method uses strict equality operator (===) for comparison, therefore, it doesn’t work with  NaN  as shown in the following example:

Comments
  • Do you want to merge the two objects hello and qaz?
  • Nope I don't. I want to have a list of objects in an array.
  • Ah okay! You want to know the position of the whole object in the array, which has a defined property.
  • I found a very simple function to solve this exact problem with this SO answer: var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor); var objectFound = array[elementPos]; [link] (stackoverflow.com/a/16100446/1937255)
  • ES6 Array.indexOf is better than accepted answer (if ES6 works for you) - see full example below
  • This should honestly be the accepted answer. Most browsers nowadays support Array.prototype.map()
  • It's not supported by IE8 but, if that's not a problem, this is the best solution.
  • Um... isn't it worth noting that Array.prototype.map() creates a whole new array containing the mapped items? So, if you've got an array with 1000 elements, you've created another array with 1000 elements first, then search it? It would be worthwhile I think to see the performance of this method vs. a simple for loop. Especially when you're running on a mobile platform with limited resources.
  • @Doug Although your point about performance is indeed correct, who in their right mind would replace one line of code with seven for an application that is almost by definition IO/Network bound until they'd profiled for bottlenecks?
  • Technically a minified js file is also one line ;D