filter method react code example

Example 1: filter array react

<div>
  {people.filter(person => 
    person.age < 60).map(filteredPerson => (
    <li>
      {filteredPerson.name}
    </li>
  ))}
</div>

Example 2: react filter

import React from 'react';

const people = [
  {
    name: 'James',
    age: 31,
  },
  {
    name: 'John',
    age: 45,
  },
  {
    name: 'Paul',
    age: 65,
  },
  {
    name: 'Ringo',
    age: 49,
  },
  {
    name: 'George',
    age: 34,
  }
];

function App() {
  return (
    <div>
      {people.filter(person => person.age < 60).map(filteredPerson => (
        <li>
          {filteredPerson.name}
        </li>
      ))}
    </div>
  );
}

export default App;

Example 3: array filter

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

Example 4: filter() array of objects on change react

const handleChange = (e) => {
      const id = hospitalsDetails.filter(obj => obj.hospitalName == e.target.value)
      setCurrentApp({ ...currentApp, [e.target.id]: e.target.value, ["hospitalID"]: id.hospitalID })  
}

Example 5: js filter items by index

let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])