indexof object array javascript code example

Example 1: javascript indexOf object value in array

// Get index of object with specific value in array
const needle = 3; // needle
const haystack = [{ id: 1 }, { id: 2 }, { id: 3 }]; // haystack
const index = haystack.findIndex(item => item.id === needle);

Example 2: using index of on array of objects

arr = [{x: "a", y: 1}, {x: "something", y: 2}]
arr.findIndex(obj => obj.x === "a" && obj.y === 1);

Example 3: indexof object javascript

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

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

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