Find() method in React – askavy

0
14


Views:
6

Call the find() method on the array, passing it a function. The find() method returns the first value in the array that satisfies the condition.

const App = () => 
  const myArr = [
     id: 1, country: "India" ,
     id: 2, country: "Germany" ,
     id: 3, country: "India" 
  ];

  //  Find object that matches condition
  const found = myArr.find((obj) => 
    return obj.id === 1;
  );


  return (
    <div>
      found && (
        <div>
          <h2>id: found.id</h2>
          <h2>country: found.country</h2>
        </div>
      )
      <hr />
    </div>
  );
;

export default App;

To find multiple objects that satisfy a condition

Use the filter() method to find multiple objects that satisfy a condition in an array in React. The filter method takes a function as a parameter and returns an array containing only the elements that satisfy the condition.

const App = () => 
  const arr = [
     id: 1, country: "India" ,
     id: 2, country: "Germany" ,
     id: 3, country: "India" 
  ];

  //  Find multiple objects that satisfy condition
  const filtered = arr.filter((obj) => 
    return obj.country === "India";
  );

  return (
    <div>
      /*  render array of objects */
      filtered.map((obj) => 
        return (
          <div key=obj.id>
            <h2>id: obj.id</h2>
            <h2>country: obj.country</h2>
          </div>
        );
      )
    </div>
  );
;

export default App;
filter4

Let us know if you liked the post. That’s the only way we can improve.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here