How to use filter() method In Javascript

You may access an array of items and create a new array in JavaScript by using the map() function. The map() function calls a given function on each element of the original array, creating a new array with the results.

Syntax:

arrayName.filter(function(item) {
console.log(item);
});

Example: The code below demonstrates how we can use the filter function to access the elements of the array of objects. It also shows how we can get a specific object from the array of objects using the clause in the filter function:

Javascript




// Array of objects
let objArr = [
    {
        name: 'john',
        age: 12,
        gender: 'male'
    },
    {
        name: 'jane',
        age: 15,
        gender: 'female'
    },
    {
        name: 'julie',
        age: 20,
        gender: 'trans'
    }
];
 
console.log("Accessing the Array using the forEach loop:")
objArr.filter(function (item) {
    console.log(item);
});
console.log("Using the Filer method to acces value")
const search = objArr.filter(function (item) {
    return item.name === 'jane';
});
console.log(search);


Output

Accessing the Array using the forEach loop:
{ name: 'john', age: 12, gender: 'male' }
{ name: 'jane', age: 15, gender: 'female' }
{ name: 'julie', age: 20, gender: 'trans' }
Using the Filer method to ...


How to Access Array of Objects in JavaScript ?

In this article, we are going to learn how we Access an Array of Objects in JavaScript. An array of objects in JavasScript is a collection of elements that individually hold a number of properties and values.

How to Access an Array of Objects in JavaScript?

The approaches to access the array of objects in JavaScript are:

Table of Content

  • Using the Brackets notation
  • Using the DOT notation
  • Using the for..in loop
  • Using forEach Loop
  • Using map() method
  • Using filter() method

Similar Reads

Using the Brackets notation

Using bracket notation and the object’s desired index, you can access an object in an array. In type, the whole object is accessed and only one of the properties of a specific object can’t be accessed....

Using the DOT notation

...

Using the for..in loop

This method can’t be used directly to access the array of objects but we have to use it together with the bracket notation. With this method, we can access any specific property of a particular object in the array of objects but not the whole object....

Using forEach Loop

...

Using map() method

The for..in loop is a type of loop that is used in JavaScript and this can be used pretty well in accessing elements of the array. By this method, you can access both the whole elements and the properties inside the objects....

Using filter() method

...

Contact Us