简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM