Dániel Boros
Dániel Boros

Reputation: 403

How can I sort a JavaScript array by specific criteria?

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?

Upvotes: 1

Views: 108

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

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);

Upvotes: 2

Related Questions