Sobes.tech
Junior

What is the difference between the filter and find methods in JavaScript?

sobes.tech AI

Answer from AI

  • filter(): Returns a new array containing all elements of the original array for which the callback function returned true. If no elements satisfy the condition, an empty array is returned.
  • find(): Returns the first element of the original array for which the callback function returned true. If no element satisfies the condition, undefined is returned.
Method Return value Number of elements in the result
filter() A new array (even if empty) Zero, one, or multiple
find() The value of the first found element or undefined Zero (if not found) or one

Example of filter:

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
// evenNumbers will be [2, 4, 6]

Example of find:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Alice' }
];
const firstAlice = users.find(user => user.name === 'Alice');
// firstAlice will be { id: 1, name: 'Alice' }