How can I filter an array of objects by specific attributes

0 votes
With the help of code, can you tell me How I can filter an array of objects by specific attributes?
Feb 10 in Java-Script by Ashutosh
• 17,360 points
41 views

1 answer to this question.

0 votes

You can use the filter() method. The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Here's an example of how to filter an array of objects by specific attributes:

const users = [

  { id: 1, name: 'Alice', age: 25 },

  { id: 2, name: 'Bob', age: 30 },

  { id: 3, name: 'Charlie', age: 25 },

  { id: 4, name: 'David', age: 35 }

];

// Filter users by age = 25

const filteredUsers = users.filter(user => user.age === 25);

console.log(filteredUsers);

In this example, the array users is filtered by the age attribute, and only those with age === 25 are included in the filteredUsers array.

You can filter by multiple attributes by combining conditions:

// Filter users by age = 25 and name starts with 'A'

const filteredUsers = users.filter(user => user.age === 25 && user.name.startsWith('A'));

console.log(filteredUsers);

This will return all users who are 25 years old and have a name starting with 'A'.

answered Feb 10 by Navya

Related Questions In Java-Script

0 votes
1 answer

How can I check the existence of an element in jQuery?

Hello @ Arpit In JavaScript, everything is 'truthy' or ...READ MORE

answered Sep 8, 2020 in Java-Script by Niroj
• 82,840 points
963 views
0 votes
1 answer

How can I determine the type of an HTML element in JavaScript?

Hello @kartik, nodeName is the attribute you are looking ...READ MORE

answered Oct 8, 2020 in Java-Script by Niroj
• 82,840 points
2,582 views
0 votes
1 answer
0 votes
1 answer

How can I call PHP functions by JavaScript?

Hello @kartik, You can do Ajax request to ...READ MORE

answered Jul 6, 2020 in Java-Script by Niroj
• 82,840 points
15,448 views
0 votes
1 answer
0 votes
1 answer

Is JavaScript processing too fast for effective DOM manipulation?

JavaScript's processing speed is generally sufficient for ...READ MORE

answered Feb 10 in Java-Script by Navya
43 views
0 votes
1 answer

How do I delete a specific element from an array in JavaScript?

You can use the splice() method. Code: let arr ...READ MORE

answered Jan 10 in Java-Script by Navya
84 views
0 votes
1 answer

How can I implement user authentication with JWT in an Express.js app?

In an Express.js application, you can use ...READ MORE

answered Dec 17, 2024 in Java-Script by Navya
85 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP