How to write code to understand it?

function findPostById(postId, posts) {
  return posts.find((post) => post.postId === postId)
}

const posts = [
  { postId: 1355, commentsQuantity: 5 },
  { postId: 5131, commentsQuantity: 13 },
  { postId: 6134, commentsQuantity: 2 },
]

console.log(findPostById(6134, posts)) // { postId: 6134, commentsQuantity: 2 }

console.log(findPostById(4511, posts)) // undefined

As always, I don’t understand this form of writing code, who can rewrite the code to make it clear, for example, I don’t understand this line

return posts.find((post) => post.postId === postId)

Let’s try this to start with…

let output = [];
posts.forEach((post) => { 
   if (post.postID === postSearchID) { 
     output.push(post); 
   } 
});
return output;

EDIT: Actually it’s dumbfire searching a single entry, so it’s ACTUALLY…

posts.forEach((post) => { 
   if (post.postID === postSearchID) { 
     return post; 
   } 
});
return undefined;

Does this help?

function findPostById(postId, posts) {
  const foundPost = posts.find(function(post) {
    if (post.postId === postId) {
      return true;
    }
  });

  return foundPost;
}

Or if written with a loop.

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
}

Here are the MDN Docs for Array.find

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

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.