Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!