Created
June 6, 2016 18:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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