javascript / beginner
Snippet
Finding Specific Items with Array.find()
The find method returns the first element in the provided array that satisfies the testing function. It is commonly used in Next.js to select a single item from a list based on an ID from the URL.
snippet.js
1
2
3
function getPostById(posts, targetId) {return posts.find(post => post.id === targetId);}
nextjs
Breakdown
1
posts.find(...)
Searches the array for a single match.
2
post => post.id === targetId
The logic that compares each post's ID with the ID we are looking for.