React by Patrik

Filtering Data by Single Criteria in JavaScript

Overview: Filtering an array based on specific attributes (e.g., gender or language) allows you to retrieve only the relevant entries. This Snipp demonstrates how to use the filter() method in JavaScript to extract items that meet a single criterion.

Implementation:

// Filter by gender
const maleNames = namesWithAttributes.filter(person => person.gender === "male");
console.log(maleNames);
// Output: [{ name: "Norbert", gender: "male", language: "German" }, { name: "Henrik", gender: "male", language: "Swedish" }, { name: "Claus", gender: "male", language: "Danish" }]

Here, we filter the array to return only the objects where the gender is male. The filter() method is powerful for searching through arrays based on any condition.

JavaScript
Filter

Comments