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": "9 - Mar - 2024","target": "16 - Mar - 2024","late": "23 - Mar - 2024"},
{"tp": "Month 2","early": "8 - Apr - 2024","target": "15 - Apr - 2024","late": "15 - 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.
2
Answers
This will give you your desired output.
Small breakdown:
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder
Use
Array.from()
to create a new array with the length of original array / number of keys (keysLen
). For each item in the new array, slice a chunk with the size ofkeyLen
from the original array, map it to [key, value] tuples, and convert it to an object usingObject.fromEntries()
: