Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop through array to add keys to every nth element

I have an array

    super = ["Month 1","22 - Feb - 2024","29 - Feb - 2024","7 - Mar - 2024",  "Month 2","23 - Mar - 2024","30 - Mar - 2024","6 - Apr - 2024"].

I’d like to add the following keys to every 4 elements:

    keys=["tp","early","target","late"]

My final array would look like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    final=[tp:"Month 1",early:"22 - Feb - 2024",target:"29 - Feb - 2024",late:"7 - Mar - 2024", tp:"Month 2",early:"23 - Mar - 2024",target:"30 - Mar - 2024",late:"6 - Apr - 2024"]

.map() might be an option, but I’m not sure how to loop for every 4th element and I’m also not real familiar that. I think something like for (var i = 0; i < super.length; i += 4) {stuff} would work, but not sure what to do in the ‘stuff’ portion.

>Solution :

This will give you your desired output.

super.map((s, i) => ({[keys[i%4]]: s}))

Small breakdown:

super.map((s, i) => {
  //we used remainder operator[1] here.
  const correctKey = keys[i % 4];
  //this is the syntax used for assigning object key from string value.
  return { [correctKey]: s };
});

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading