Created
November 14, 2017 23:39
-
-
Save aderaaij/6059b9d2221d5fe90a647bd7a94e8589 to your computer and use it in GitHub Desktop.
`array.find()` and `array.findIndex()` do pretty much what you expect. They go over each item of an array so you can return the value you want, which is especially handy when you're looking for something in particular in an array of objects (and even more handy when that array of objects is keyless. Example time
This file contains hidden or 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
const users = [ | |
{ | |
"_id": "5a0b7a6441a687091332f11b", | |
"index": 0, | |
"guid": "0d3bba05-ecde-4237-b53e-0bd474239ee2", | |
"isActive": false, | |
"balance": "$2,144.22", | |
"picture": "http://placehold.it/32x32", | |
"age": 32, | |
"eyeColor": "green", | |
"name": "Lavonne Finley", | |
"gender": "female" | |
}, | |
{ | |
"_id": "5a0b7a647febf037be5daaa7", | |
"index": 1, | |
"guid": "20311487-7e92-48ba-a26f-d627d7cb3686", | |
"isActive": false, | |
"balance": "$2,284.92", | |
"picture": "http://placehold.it/32x32", | |
"age": 21, | |
"eyeColor": "blue", | |
"name": "Austin Mullins", | |
"gender": "male" | |
}, | |
{ | |
"_id": "5a0b7a64ed89bcc74e06d289", | |
"index": 2, | |
"guid": "211f93e7-73b9-46a5-80db-bc04908af917", | |
"isActive": false, | |
"balance": "$1,581.91", | |
"picture": "http://placehold.it/32x32", | |
"age": 32, | |
"eyeColor": "brown", | |
"name": "Henderson Bryant", | |
"gender": "male" | |
}, | |
{ | |
"_id": "5a0b7a64fdb857c6a2b5767a", | |
"index": 3, | |
"guid": "2e1e89de-06c2-45dd-b92e-afb4a9702026", | |
"isActive": true, | |
"balance": "$3,069.90", | |
"picture": "http://placehold.it/32x32", | |
"age": 35, | |
"eyeColor": "blue", | |
"name": "Mia House", | |
"gender": "female" | |
} | |
] | |
// Return the user with the matching id | |
const user = users.find(user => user._id === '5a0b7a64ed89bcc74e06d289'); | |
console.log(user); | |
// Return the index of the user with the matching ID | |
const userIndex = users.findIndex(user => user._id === '5a0b7a64ed89bcc74e06d289'); | |
console.log(userIndex); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment