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
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