Search code examples
javascriptarraysloopskey

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

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.


Solution

  • 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 of keyLen from the original array, map it to [key, value] tuples, and convert it to an object using Object.fromEntries():

    const fn = (keys, data = []) => {
      const keysLen = keys.length
      
      return Array.from(
        { length: data.length / keysLen }, // the new arrays length
        (_, i) => 
          Object.fromEntries( // create object from an array of [key, value] tuples
            data.slice(i * keysLen, (i + 1) * keysLen) // get keysLen items from original array
              .map((v, idx) => [keys[idx], v]) // map them to [key, value] tuples
          )
      )
    }
    
    const data = ["Month 1","22 - Feb - 2024","29 - Feb - 2024","7 - Mar - 2024",  "Month 2","23 - Mar - 2024","30 - Mar - 2024","6 - Apr - 2024"]
    const keys = ["tp","early","target","late"]
    
    const result = fn(keys, data)
    
    console.log(result)