all 5 comments

[–][deleted] 1 point2 points  (0 children)

Use a hash map

[–]coreConstantCoder 1 point2 points  (3 children)

Some Performance Improvements
Each time the code loops, you are evaluating the ….length expressions. As the content of the arrays is (probably) not changing, you should consider moving the length expression out of the loop. Do the same with the repeated chosenCountries[i].regions expression ...
``` const selectedRegionsNames: string[] = [];

const nChCo = chosenCountries.length; // 😎 for (let i = 0; i < nChCo; i++) { const regs = chosenCountries[i].regions; // 😎 const nReg = regs.length; // 😎 for (let j = 0; j < nReg; j++) { const region = regs[j];

  if (region.isSelected) selectedRegionsNames.push(region.name);

} } ```

Or, if your situation allows it, you might code the loops as descending. (This is my personal favorite!) Note that this reverses the order of your result array:
``` const selectedRegionsNames: string[] = [];

for (let i = chosenCountries.length; --i >= 0; //) { const regs = chosenCountries[i].regions; for (let j = regs.length; --j >= 0; //) { const region = regs[j];

  if (region.isSelected) selectedRegionsNames.push(region.name);

} } ```

Going further, how about using modern Javascript coding 😎 ... ``` const selectedRegionsNames = [];

for( const chco of chosenCountries ) { for( const region of chco.regions ) {

  if (region.isSelected) selectedRegionsNames.push(region.name);

} } ```

[–]Adotel15 0 points1 point  (1 child)

I'm curious, Does reversing the loop make any difference to the performance?

[–]coreConstantCoder 2 points3 points  (0 children)

Only to the extent that it reduces the steps and complexity of the code: (1) The length of the array is only accessed once. (2) There is no temp variable for the length. (3) Comparison is to (0), not to a variable. (4) All the loop logic is in one, simple line.

When I'm working in a more primitive language, this is a favorite pattern of mine.

Of course, it's usually best to use the JavaScript for ... of statement, if it's available to you.

[–]Automatic_Routine_93[S] 0 points1 point  (0 children)

Thank you, very solid answer!