1

I have an array like:

[0,0,1,1,0,0,2,2,2,0...]

I have to pass for each element a letter in this form:

[A, B, C1, C2, D, E, F1, F2, F3, G...]

When the value is zero, or undefined or null need a new letter, otherwise need a new one again but as times as the same number stays there. There are two of 1 then I need C1, C2, later is there three of 2 so I need F three times.

Can you give me some hints to solve this issue?

7
  • What have you tried so far? Commented Jun 29, 2021 at 14:54
  • Also, what happens if you have [0, 0, 1, 1, 2, 2]? Do you start a new letter sequence for the 2s or continue the old one? Commented Jun 29, 2021 at 14:54
  • 2 needs a new letter yeah. :) Commented Jun 29, 2021 at 14:55
  • What is the expected output? A flat array like this: [C1, C2, F1, F1, F2, F2, ...]? Commented Jun 29, 2021 at 14:56
  • What if out of the range like after Z ? Commented Jun 29, 2021 at 14:58

1 Answer 1

2

You could take a closure over letter and count and return eiter the same letter as before with count or just the letter.

const
    values = [0, 0, 1, 1, 2, 2, 3, 3, 3, 0],
    result = values.map(((letter, count) => (v, i, { [i - 1]: prev }) => {
        if (v) {
            if (prev && v !== prev) {
                ++letter;
                count = 1;
            }
            return letter.toString(36).toUpperCase() + count++;
        }
        if (count !== 1) ++letter;
        count = 1;
        return (letter++).toString(36).toUpperCase();
    })(10, 1));

console.log(...result);

Sign up to request clarification or add additional context in comments.

5 Comments

I have stuck with your script a bit in that case when I have an array like for example [0, 0, 1, 1, 2, 2, 3, 3, 3, 0]. I get results [A, B, C1, C2, C3, C4, C5, C6, C7, D] so at 1 and 2 and 2 and 3 don't change the letter.
@DánielBoros, it needs another check. please see edit.
it seems good, but the number should start from 1 when the letters are changed. Sorry I was not exact.
I think I should take count = 1 in the second if statement and everything will be perfect.
I need for result an array like this: [A B C1 C2 D1 D2 E1 E2 E3 F]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.