Obtuve los datos a continuación y he estado luchando para eliminar algunos objetos que tienen valores de taxonomy duplicados pero mantienen la longitud más larga de los terms .
clickedFiltrar datos
0: {taxonomy: 'brands', operator: 'IN', terms: Array(1)} 1: {taxonomy: 'brands', operator: 'IN', terms: Array(2)} 2: {taxonomy: 'paColors', operator: 'IN', terms: Array(1)} 3: {taxonomy: 'paColors', operator: 'IN', terms: Array(2)} 4: {taxonomy: 'paLengths', operator: 'IN', terms: Array(1)}datos esperados
0: {taxonomy: 'brands', operator: 'IN', terms: Array(2)} 1: {taxonomy: 'paColors', operator: 'IN', terms: Array(2)} 2: {taxonomy: 'paLengths', operator: 'IN', terms: Array(1)} He probado un new Set como el siguiente:
const uniq = new Set(clickedFilter.map(e => e.taxonomy)); const res = Array.from(uniq).map(e => e); let uniqArr = []; clickedFilter.filter(f => { res.filter(r => { console.log('r', r); if (r === f.taxonomy) uniqArr.push(f); }); }); pero esto me ha dado los mismos datos con los datos de clickedFilter .
Además, probé usando el filter
const test = clickedFilter.filter((obj, idx, self) => { return self.filter(s => s.taxonomy === obj.taxonomy && s.terms.length > obj.terms.length); });pero esto me muestra solo una matriz vacía.
Siento que esto debe ser simple y no tan complejo, pero no sé qué hacer. Agradeceré si alguien me indica la dirección.
Puede usar una agrupación simple 'agrupar por' por taxonomy y comparar terms.length .
const input = [{ taxonomy: 'brands', operator: 'IN', terms: Array(1) }, { taxonomy: 'brands', operator: 'IN', terms: Array(2) }, { taxonomy: 'paColors', operator: 'IN', terms: Array(1) }, { taxonomy: 'paColors', operator: 'IN', terms: Array(2) }, { taxonomy: 'paLengths', operator: 'IN', terms: Array(1) },]; const result = Object.values( input.reduce((a, o) => { if (a[o.taxonomy] === undefined || o.terms.length > a[o.taxonomy].terms.length) { a[o.taxonomy] = o; } return a; }, {})); console.log(result);