skip to Main Content

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


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

    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search