Introduction
In this lab, we will explore JavaScript programming and learn how to use the Array.prototype.reduce(), Array.prototype.filter(), and Array.prototype.map() methods together to create a function that filters an array of objects based on a condition and also filters out unspecified keys. This lab will help improve our understanding of functional programming in JavaScript and how to manipulate arrays of objects in a concise and efficient manner.
Filtering Objects by Condition and Keys
To filter an array of objects based on a condition, while also filtering out unspecified keys, use the reducedFilter() function.
Here are the steps to follow:
Use
Array.prototype.filter()to filter the array based on the predicatefnso that it returns the objects for which the condition returned a truthy value.Use
Array.prototype.map()on the filtered array to return the new object.Use
Array.prototype.reduce()to filter out the keys which were not supplied as thekeysargument.
const reducedFilter = (data, keys, fn) =>
data.filter(fn).map((el) =>
keys.reduce((acc, key) => {
acc[key] = el[key];
return acc;
}, {})
);
Here is an example usage of the reducedFilter() function:
const data = [
{
id: 1,
name: "john",
age: 24
},
{
id: 2,
name: "mike",
age: 50
}
];
reducedFilter(data, ["id", "name"], (item) => item.age > 24);
// Output: [{ id: 2, name: 'mike'}]
To start practicing coding, open the Terminal/SSH and type node.
Summary
Congratulations! You have completed the Filter Matching and Unspecified Values lab. You can practice more labs in LabEx to improve your skills.