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

Generate array with values A1, A2, A3, B1, B2, B3… etc?

I’m trying to generate an array of objects where it outputs an array looking like this:

[
    {
      _id: 2,
      label: 'A1'
    },
    {
      _id: 3,
      label: 'A2'
    },
    {
      _id: 4,
      label: 'A3'
    },
    {
      _id: 5,
      label: 'B1'
    },
    {
      _id: 6,
      label: 'B2'
    },
    {
      _id: 7,
      label: 'B3'
    }
  ]

And all the way up to letter "G"… However, I cant quite to seem to wrap my head around how to generate this automatically. So far I’ve come up with this, but in my output it’s skipping letters, and isn’t generating the correctly 🙂 Could use some help on this.

What I have so far:

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

function nextChar(c) {
   return String.fromCharCode(c.charCodeAt(0) + 1);
}

const supersetOptions = computed(() => {
  const maxGroup = 6;
  const maxItems = 12;
  let defaultLetter = 'a';

  return Array.from({ length: maxItems }, (value, index) => {
    const currentLetter = nextChar(defaultLetter)
    defaultLetter = nextChar(currentLetter);
    return {
      label: `${currentLetter}${index + 1}`,
      value: `${currentLetter}${index + 1}`
    };
  });
})

>Solution :

You appear to start the _id from 2, but I’ve assumed this is a typo. If not, then just i+2 instead of i+1 on line 8.

You also have different property names between what you say you want, and what your code is attempting to produce. This matches what you said you wanted.

function generate(count) {
    const results = []

    for(let i = 0 ; i < count ; i++) {
        const letter = String.fromCharCode(65 + (i / 3))
        const delta = (i % 3) + 1
        results.push({
            _id: i+1,
            label: `${letter}${delta}`
        })
    }

    return results
}

console.log(generate(21))
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