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

167
Views
How to improve code using reduce instead two loops?

I tried to improve code using reducing:

private getAllRegistryObjects(registry: RegistryGeneric) {
    const registryLayerItemGeneric = [];
    registry.RegistryLayers.forEach((layer) => {
        layer.items.forEach((item) => {
            registryLayerItemGeneric.push(item);
        });
    });

    return registryLayerItemGeneric;
}

I have tried this:

return registry.RegistryLayers.reduce(function(previousValue, currentValue, currentIndex, array) {
  return previousValue.concat(currentValue.items.flat());
}, [])

But it returns me empty array

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

0

Your code works:

var registry = {RegistryLayers: [
{ items: ['some', 'item'] },
{ items: ['other', 'things'] }
]};
var res = registry.RegistryLayers.reduce(function(previousValue, currentValue, currentIndex, array) {
  return previousValue.concat(currentValue.items.flat());
}, []);
console.log(res)

says:

['some', 'item', 'other', 'things']

To reduce need to repeatedly extend/copy the array, you can use flatMap instead if you just want them all joined up:

return registry.RegisteryLayers.flatMap((x) => x.items.flat());
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!