function findPostById(postId, posts) {
// loop through all posts
for (let i = 0; i < posts.length; i+=1) {
// do we have a matched postId?
if (posts[i] === postId) {
return posts[i] // yes, stop immediately and return that id
}
}
// we have finished the loop without finding a matched postId
// so return undefined
return undefined // not really necessary as this will be returned anyway
}
I don’t know if this confuses things, but elaborating on the above loop, this is basically how Array.find works
// This is what Array.find is doing
function find(arr, callback) {
// loop through the given array
for (let i = 0; i < arr.length; i+=1) {
// pass in each item to the given function
// and test to see if the function returns true
if (callback(arr[i])) === true) {
return arr[i] // true, so return item
}
}
// no matches to 'true'
return undefined
}
// example using find
function findPostById(posts, postId) {
const foundId = find(
// the array of posts.
posts,
// this is the function to be called on each post.
function (post) {
if (post.postId === postId) return true
}
)
return foundId
}
For some reason, in every code there is an entry where I do not understand how it works, for example, return foundPost; why doesn’t the code work without it? if the block contains true, then it should output true, but without undefined, and here the error appears immediately