Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- array.find((element, index, array) => {
- return condition;
- });
- // Array
- const numbers = [5, 10, 15, 20];
- const found = numbers.find(num => num > 10);
- console.log(found); // 15 ✅ (first one > 10)
- // Object
- const users = [
- { id: 1, name: "Alice" },
- { id: 2, name: "Bob" },
- { id: 3, name: "Charlie" }
- ];
- const user = users.find(u => u.id === 2);
- console.log(user); // { id: 2, name: "Bob" }
- // No Match
- const result = [1, 2, 3].find(num => num > 5);
- console.log(result); // undefined ❗️
- // React
- const UserProfile = ({ id, users }) => {
- const user = users.find(u => u.id === id);
- return user ? <h2>{user.name}</h2> : <p>User not found</p>;
- };
- // Find a product by ID in a shopping cart
- const cart = [
- { id: 1, name: "Shirt", quantity: 2 },
- { id: 2, name: "Shoes", quantity: 1 }
- ];
- const productId = 2;
- const item = cart.find(product => product.id === productId);
- console.log(item);
- // { id: 2, name: "Shoes", quantity: 1 }
- // Find a user by username or ID
- const users = [
- { id: 101, username: "alice" },
- { id: 102, username: "bob" }
- ];
- const currentUser = users.find(u => u.username === "bob");
- console.log(currentUser);
- // { id: 102, username: "bob" }
- // Find a blog post by slug or ID
- const posts = [
- { id: 1, slug: "intro-to-react", title: "React Basics" },
- { id: 2, slug: "advanced-hooks", title: "React Hooks" }
- ];
- const post = posts.find(p => p.slug === "advanced-hooks");
- console.log(post.title); // "React Hooks"
- // Find an event happening on a specific date
- const events = [
- { name: "Hackathon", date: "2025-04-20" },
- { name: "Launch", date: "2025-05-01" }
- ];
- const today = "2025-04-20";
- const eventToday = events.find(e => e.date === today);
- console.log(eventToday?.name); // "Hackathon"
- // React Example
- import React, { useState } from "react";
- const App = () => {
- const [selectedId, setSelectedId] = useState(2); // Simulate selected user ID
- const users = [
- { id: 1, name: "Alice", age: 25, role: "Admin" },
- { id: 2, name: "Bob", age: 30, role: "Editor" },
- { id: 3, name: "Charlie", age: 22, role: "Viewer" },
- ];
- // 🔍 Find the user using `.find()`
- const user = users.find((u) => u.id === selectedId);
- return (
- <div style={{ padding: "1rem" }}>
- <h1>User Profile</h1>
- {user ? (
- <div>
- <p><strong>Name:</strong> {user.name}</p>
- <p><strong>Age:</strong> {user.age}</p>
- <p><strong>Role:</strong> {user.role}</p>
- </div>
- ) : (
- <p>User not found</p>
- )}
- </div>
- );
- };
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement