Last active
July 24, 2022 07:30
-
-
Save MrAndrewMal/2b762557d428295606ef69335e9c9120 to your computer and use it in GitHub Desktop.
Filter array items by choosen fields
This file contains 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
const users = [ | |
{ | |
id: 1, | |
name: 'Leanne Graham', | |
username: 'Bret', | |
email: 'Sincere@april.biz', | |
}, | |
{ | |
id: 2, | |
name: 'Ervin Howell', | |
username: 'Antonette', | |
email: 'Shanna@melissa.tv', | |
}, | |
{ | |
id: 3, | |
name: 'Bret Bauch', | |
username: 'Samantha', | |
email: 'Nathan@yesenia.net', | |
}, | |
] | |
const todo = [ | |
{ | |
userId: 1, | |
id: 1, | |
title: 'delectus aut autem', | |
completed: false, | |
}, | |
{ | |
userId: 1, | |
id: 2, | |
title: 'quis ut nam facilis et officia qui', | |
completed: false, | |
}, | |
{ | |
userId: 1, | |
id: 3, | |
title: 'fugiat veniam minus', | |
completed: false, | |
}, | |
] | |
function filteredItems(filter = '', items = [], fields = []) { | |
return filter ? items.filter((u) => fields.some((f) => u[f].toLowerCase().includes(filter.toLowerCase()))) : items | |
} | |
const searchUser = filteredItems('Bret', users, ['name','username']) | |
// [ { id: 1, name: 'Leanne Graham', username: 'Bret', email: 'Sincere@april.biz' },{ id: 3, name: 'Bret Bauch', username: 'Samantha', email: 'Nathan@yesenia.net' } ] | |
const searchTodo = filteredItems('quis', todo, ['title']) | |
// [ { userId: 1, id: 2, title: 'quis ut nam facilis et officia qui', completed: false } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment