Skip to content

Instantly share code, notes, and snippets.

@dejurin
Last active February 25, 2024 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dejurin/78dad620b0f88d01fea8a7dca9bbaa7d to your computer and use it in GitHub Desktop.
Save dejurin/78dad620b0f88d01fea8a7dca9bbaa7d to your computer and use it in GitHub Desktop.
Filters a 2D array of data objects by a keyword.
/*
That function make filter by this map.
[
{
"si": [
{
"millimeter": "0.001"
}
]
},
{
"extra": [
{
"megameter": "1000000"
}
]
}
]
*/
/**
* Represents a data type with key-value pairs, where the value is an array of the same data type.
*/
type DataType = {
[key: string]: DataType[];
};
/**
* Filters a 2D array of data objects by a keyword.
*
* @param data - The array of data objects to filter.
* @param keyword - The keyword to filter by.
* @returns An array of filtered data objects.
*/
export default function filterDataByKey2D(data: DataType[], keyword: string) {
return data
.map((obj) => {
// Get the category key.
const categoryKey = Object.keys(obj)[0];
// Get the items of the category.
const items = obj[categoryKey as keyof typeof obj];
// Filter the items by the keyword.
const filteredItems = items.filter((item: {}) => {
return Object.keys(item).some((key) => key.includes(keyword));
});
// Return the category key and the filtered items.
return filteredItems.length > 0 ? { [categoryKey]: filteredItems } : null;
})
.filter((obj) => obj !== null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment