'JavaScript: Remain the longest length of array by removing duplicate values in object array

I have got the data below, and have been struggling to remove some objects which have duplicate values of taxonomy but keep the longest length of terms.

clickedFilter data

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)}

expected data

0: {taxonomy: 'brands', operator: 'IN', terms: Array(2)}
1: {taxonomy: 'paColors', operator: 'IN', terms: Array(2)}
2: {taxonomy: 'paLengths', operator: 'IN', terms: Array(1)}

I have tried new Set like below:

    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);
      });
    });

but this has given me the same data with clickedFilter data.

Also, I gave a try using filter

    const test = clickedFilter.filter((obj, idx, self) => {
      return self.filter(s => s.taxonomy === obj.taxonomy && s.terms.length > obj.terms.length);
    });

but this shows me only an empty array.

I feel like this must be simple and not that complex, but I am at a loss for what to do. I will be grateful if anybody lets me know the direction.



Solution 1:[1]

You can use a simple 'group-by' grouping by taxonomy and comparing 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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pilchard