Skip to content

Instantly share code, notes, and snippets.

@mikemcbride
Created June 6, 2016 18:02
Show Gist options
  • Save mikemcbride/cd6c576137b5e7af10c1ae9112e66a36 to your computer and use it in GitHub Desktop.
Save mikemcbride/cd6c576137b5e7af10c1ae9112e66a36 to your computer and use it in GitHub Desktop.
Get the index of an object in an array based on a property
function getObjectIndex (array, key, term) {
return array.indexOf(array.find(it => it[key] === term))
}
// Example: find the index of the object where object.foo == 'apple'
const myArray = [
{
'foo': 'foo',
'bar': 'bar',
'baz': 'baz'
},
{
'foo': 'apple',
'bar': 'banana',
'baz': 'orange'
},
{
'foo': 'cat',
'bar': 'dog',
'baz': 'bear'
}
];
console.log(getObjectIndex(myArray, 'foo', 'apple')) // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment