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

240
Views
convert repeating code into function- JavaScript?

Am trying to bind values just to view. my code is working so far. but I'm repeating the same nested forEach 3 times. so Sonarcube will definitely mark it as duplicate. Could someone tell me how to avoid code repetition ?

Is there any way to optimize the below repeated codes and convert them as a generic function in JavaScript?

response.mainDish.forEach(element => {
    this.selectedMainDish.forEach(ele => {
        if (ele?.id === element.id) {
            this.bindMainDish.push(ele?.mainDish);
        }
    });
});

response.sideDish1?.forEach(element => {
    this.selectedSideDish1List.forEach(ele => {
        if (ele.id === element.id) {
            this.bindSideDish1.push(ele.sideDish1);
        }
    });
});

response.sideDish2?.forEach(element => {
    this.selectedSideDish2.forEach(ele => {
        if (ele.id === element.id) {
            this.bindSideDish2.push(ele.sideDish2);
        }
    });
});
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can make a generic function using dynamic property names

let functionDoThis = function( mainDish , selectedMainDish, bindMainDish){
response[mainDish]?.forEach(element => {
    this[selectedMainDish]?.forEach(ele => {
        if (ele?.id === element.id) {
            this[bindMainDish]?.push(ele[mainDish]);
        }
    });
});

}

functionDoThis('mainDish', 'selectedMainDish' , 'bindMainDish');
functionDoThis('sideDish1', 'selectedSideDish1List' , 'bindSideDish1');

functionDoThis('sideDish2', 'selectedSideDish2' , 'bindSideDish2');

about 4 years ago · Juan Pablo Isaza Report

0

may besomething like that...

const dish_keys =
[ {dish:'mainDish',  selected:'selectedMainDish',      bind:'bindMainDish'  }
, {dish:'sideDish1', selected:'selectedSideDish1List', bind:'bindSideDish1' }
, {dish:'sideDish2', selected:'selectedSideDish2',     bind:'bindSideDish2' }
]


for (let {dish,selected,bind} of dish_keys)
  response[dish]?.forEach(element => 
    this[selected]?.forEach(ele =>{ 
      if (ele?.id === element.id)  this[bind]?.push(ele[dish]) }
  ) );
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!