Me gustaría devolver los dos últimos objetos basados en filterArray porque filterArray contiene 'Orange' como etiquetas y 'Fruit' como tipo. pero debido a que todos mis obj contienen una serie de etiquetas, la función que incluye no funciona. (funciona solo si las etiquetas de valor son una cadena).
const filterArray = [ { type: 'type', value: ['Fruit'] }, { type: 'tags', value: ['Apple', 'Orange', 'Peach'] }, ] const obj = [ { type: 'Sweet Fruit', tags: ['Apple'] }, { type: 'Fruit', tags: ['Orange', 'Watermelon'] }, { type: 'Fruit', tags: ['Orange'] }, ] const Newresult = obj.filter(item => filterArray.every(({ type, value }) => value.includes(item[type])), ) console.log(Newresult)esta función funciona si const obj.tags no es una matriz sino una cadena.
Podrías usar lo siguiente:
// use a set in the filter so lookups happen in O(1) const filter = [ { type: "type", value: new Set(["Fruit"]) }, { type: "tags", value: new Set(["Apple", "Orange", "Peach"]) }, ]; const obj = [ { type: "Sweet Fruit", tags: ["Apple"] }, { type: "Fruit", tags: ["Orange", "Watermelon"] }, { type: "Fruit", tags: ["Orange"] }, ]; const Newresult = obj.filter((item) => ( filter.every(({ type, value }) => { // check whether the value we want to filter by is an arry if(Array.isArray(item[type])){ // yes, we are dealing with an array => check if any of the filter criteria are matched // if you want to check for all criteria use "every()" instead of "some" return item[type].some(valueInArray => value.has(valueInArray)); } // if we are not dealing with an array we need to just check one value return value.has(item[type]); }) )); console.log(Newresult);Cambios clave en su enfoque:
Set en lugar de una matriz que reduce el tiempo de búsquedas O(n) para matrices a 0(1) y, por lo tanto, acelera significativamente el algoritmo.Puede tratar cada valor de los datos como una matriz y verificar si los datos contienen un valor del filtro.
const filter = [{ type: 'type', value: ['Fruit'] }, { type: 'tags', value: ['Apple', 'Orange', 'Peach'] }], data = [{ type: 'Sweet Fruit', tags: ['Apple'] }, { type: 'Fruit', tags: ['Orange', 'Watermelon'] }, { type: 'Fruit', tags: ['Orange'] }, ], result = data.filter(o => filter.every(({ type, value }) => [] .concat(o[type]) .some(v => value.includes(v)) )); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }