Tuesday, May 27, 2025

find() and filter() in javascript

 In this explore explore implementation of find() and filter() function in JavaScript with simple example. There are various ways to extract the needed values from an array, but we'll utilize JavaScript's .find() and .filter() methods here.

find() and filter() in javascript


find() Method

  1. Purpose: Returns the first element in the array that satisfies the provided testing function.
  2. Returns: The value of the first element that passes the test, or undefined if no elements pass the test.

Syntax:

array.find(callback(element, index, array), thisArg)

Example -1 

  let numbers = [1, 2, 3, 4, 5];
  let found = numbers.find(element => element > 3);
  console.log(found); // 4


Example - 2

let users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];
let user = users.find(user => user.id === 2);
console.log(user); // { id: 2, name: 'Bob' }

filter() Method

  1. Purpose: Creates a new array with all elements that pass the test implemented by the provided function.
  2. Returns: A new array with the elements that pass the test, or an empty array if no elements pass the test.

Syntax:

array.filter(callback(element, index, array), thisArg)


Example - 1

  let numbers = [1, 2, 3, 4, 5];
  let filtered = numbers.filter(element => element > 3);
  console.log(filtered); // [4, 5]


Example -2 

let users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'Alice' }
];
let alices = users.filter(user => user.name === 'Alice');
console.log(alices); // [{ id: 1, name: 'Alice' }, { id: 4, name: 'Alice' }]


In summary, use find for locating a single element and filter for gathering multiple elements based on a condition.


No comments:

Post a Comment