I have an array that contains information. The data has a tag attribute on which I want to filter.
If the array contains data, the filter should be triggered on all data in the array. If there is no data in the array, then I get all the data from the array with data.
I need control array length for this I need to use includes for max data after filter 30
//exist array with data
const arr = [
{ "value": "food", "tag": "food" },
{ "value": "drink1", "tag": "drink" },
{ "value": "drink2", "tag": "drink" },
{ "value": "empty tag data", "tag": null }
];
//example data from request with tags for filtering
const data1 = ["food", "drink"];
const data2 = [];
function example(arrayForSearch, needToFind) {
//not work o.tag.includes(needToFind, 30)
return arrayForSearch.reduce((a, o) => (o.tag.includes(needToFind) && a.push(o.value), a), []);
}
// result (0, 1, 2) indexes from array
console.log(example(arr, data1));
// result all data from array
console.log(example(arr, data2));
o.tag.includes(needToFind)should beneedToFind.includes(o.tag)and you should also check ifneedToFindis an empty array as you want to keep the object in that case