Created
February 25, 2026 19:18
-
-
Save petergi/4f0ee6dfa93cf14cd99f8a44813646d6 to your computer and use it in GitHub Desktop.
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.pr…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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. | |
| const reducedFilter = (data, keys, fn) => | |
| data.filter(fn).map(el => | |
| keys.reduce((acc, key) => { | |
| acc[key] = el[key]; | |
| return acc; | |
| }, {}) | |
| ); | |
| 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'}] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment