javascript / beginner
Snippet
Finding Items with .find()
The .find() method searches an array and returns the very first element that matches a specific condition. It is perfect for selecting a single item from a list by its ID.
snippet.js
javascript
1
2
3
4
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];const selectedUser = users.find(user => user.id === 2);// selectedUser is { id: 2, name: 'Bob' }
react
Breakdown
1
users.find(user => user.id === 2)
Iterates through 'users' and returns the first object where the 'id' is exactly 2.