Prepare repository for merge

This commit is contained in:
Angelos Chalaris
2023-05-01 22:35:56 +03:00
parent fc4e61e6fa
commit b3ad01863a
578 changed files with 0 additions and 0 deletions

View File

@ -0,0 +1,40 @@
---
title: Filter matching and unspecified values
type: snippet
tags: [array]
cover: little-bird
dateModified: 2020-10-22T20:24:04+03:00
---
Filters an array of objects based on a condition while also filtering out unspecified keys.
- Use `Array.prototype.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value.
- On the filtered array, use `Array.prototype.map()` to return the new object.
- Use `Array.prototype.reduce()` to filter out the keys which were not supplied as the `keys` argument.
```js
const reducedFilter = (data, keys, fn) =>
data.filter(fn).map(el =>
keys.reduce((acc, key) => {
acc[key] = el[key];
return acc;
}, {})
);
```
```js
const data = [
{
id: 1,
name: 'john',
age: 24
},
{
id: 2,
name: 'mike',
age: 50
}
];
reducedFilter(data, ['id', 'name'], item => item.age > 24);
// [{ id: 2, name: 'mike'}]
```