Created
February 22, 2022 04:37
-
-
Save DavidWells/9ceeb5eea1af8a16d0f61fb72b705698 to your computer and use it in GitHub Desktop.
Super simple array of object search without referencing keys
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
// https://github.com/RajikaKeminda/multi-search/blob/main/index.js | |
// https://multi-search.vercel.app/ | |
// https://codesandbox.io/s/upbeat-goldberg-mzvzqz?from-embed=&file=/src/App.js | |
function singleKeyFilter(list, query, key) { | |
let querySanitizer = String(query).trim().toLowerCase(); | |
return list.filter( | |
(i) => String(i[key]).toLowerCase().indexOf(querySanitizer) > -1 | |
); | |
} | |
export default function multiSearch(list, query) { | |
if (Array.isArray(list) && list.length > 0) { | |
let searchList = []; | |
for (let [key] of Object.entries(list[0])) searchList = [...searchList, singleKeyFilter(list, query, key)]; | |
let set = new Set(searchList.flat()); | |
return [...set]; | |
} | |
return []; | |
} |
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
import search from 'multi-search' | |
let list = [ | |
{ name: 'Madara Uchiha', age: 25, clan: 'Uchiha Clan' }, | |
{ name: 'Kakashi Hatake', age: 26, clan: 'Hatake Clan' }, | |
{ name: 'Tsunade', age: 45, clan: 'Senju Clan' }, | |
{ name: 'Naruto Uzumaki', age: 18, clan: 'Uzumaki Clan' }, | |
{ name: 'Sakura Haruno', age: 18, clan: 'Uchiha Clan' }, | |
]; | |
console.log(search(list, 45)); // [{ name: 'Tsunade', age: 45, clan: 'Senju Clan' }] | |
console.log(search(list, 'kakashi')); // [{ name: 'Kakashi Hatake', age: 26, clan: 'Hatake Clan' }] | |
console.log(search(list, 18)); | |
//[ | |
// { name: 'Naruto Uzumaki', age: 18, clan: 'Uzumaki Clan' }, | |
// { name: 'Sakura Haruno', age: 18, clan: 'Uchiha Clan' } | |
//] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment