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

107
Views
How to remove mutation on this code Javascript?

I managed to write code which does what I need, but I want to make it clean and remove mutation of realtiveGroups.push() but don't know how to achieve it. How to remove mutation from this code?

export interface OfferCategory {
  id: string;
  name: string;
}

export interface OfferGroup {
  groupId: string;
  dependsOn: OfferCategory;
  name: string;
  rule: Rule;
  products: PosProducts[];
}

function relativesFromSubscription(groups: OfferGroup[], dependingGroups: OfferGroup[]): OfferGroup[] {
    const relativeGroups: OfferGroup[] = [];
    groups.forEach(group => {
      if (dependingGroups.some(dependingGroup => group?.dependsOn?.id === dependingGroup.groupId)) {
        relativeGroups.push(group);
      }
      if (relativeGroups.some(relativeGroup => group?.dependsOn?.id === relativeGroup.groupId)) {
        relativeGroups.push(group);
      }
    });
    return relativeGroups;
  }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Instead of doing everything in one cycle try dividing it into a few:

function relativesFromSubscription(groups: OfferGroup[], dependingGroups: OfferGroup[]): OfferGroup[] {
    const groups1 = groups.filter(group => dependingGroups.some(dependingGroup => group?.dependsOn?.id === dependingGroup.groupId));
    const groups2 = groups.filter(group => groups1.some(relGroup=> group?.dependsOn?.id === relGroup.groupId)); 
    return [...groups1, ...groups2];
}
about 4 years ago · Juan Pablo Isaza Report

0

Using your code and Array.filter

const relativeGroups: OfferGroup[] = groups.filter(group => {
    return dependingGroups.some(dependingGroup => group?.dependsOn?.id === dependingGroup.groupId) || relativeGroups.some(relativeGroup => group?.dependsOn?.id === relativeGroup.groupId)
});

Or if you want the code to be more readable you can add descriptive variables:

const relativeGroups: OfferGroup[] = groups.filter(group => {
  const hasDependingGroups = dependingGroups.some(dependingGroup => group?.dependsOn?.id === dependingGroup.groupId);

  const hasRelativeGroups = relativeGroups.some(relativeGroup => group?.dependsOn?.id === relativeGroup.groupId)

  return hasDependingGroups || hasRelativeGroups
});
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!