Hi,
To filter various data at the same time in the following table,
I'm trying to find an simple alternative to avoid nested loops for this scenario :
const carsList =
{
"id": 1,
"name" : "Fiat",
"description" : "blabla",
"options": [
{
"option" : "electric windows",
"quantity" : 4
},
{
"option" : "air bags",
"quantity" : 2
}
]
}
]
// value = e.target.value;
result = carsList.filter(
(car) =>
car.name.toLowerCase().includes(value.toLowerCase()) ||
car.description.toLowerCase().includes(value.toLowerCase()) ||
car.options.some((option) =>
option.option.toString().toLowerCase().includes(value.toString().toLowerCase())
)
);
also to filter with an array of values ( tagsExist ( the id's are the names ) ) as follows :
let tagsExist = [...document.querySelectorAll('#tags [id]')].map((elm) => elm.id);
resultResearchInPage = carsList.filter((element) =>
tagsExist.every(
(x) =>
element.name.toString().toLowerCase().includes(x) ||
element.description.toString().toLowerCase().includes(x) ||
element.options.some((option) => option.option.toString().toLowerCase().includes(x))
)
);
the "some" in the "filter" are problematic, could you help me, please ?
CodePudding user response:
If it is feasible for you, I would suggest transforming the options
array of the carList
to an object, declaring as key the option
variable, and as value the quantity
(or an object if you will need more attributes). Then you can check if option in options
, being options something like:
"options":{
"air bags":{
"quantity": 2
},
...
}
This will be checked in linear time, as key checks work similarly as with hashmaps, instead of having to loop through the whole array.
However this will only work if you have unique keys for the options and if you can transform the array to an object without more performance problems than this solution will solve.