How to Sort By Frequency And Then Filter Repeats in JavaScript – Solution

I got one question during interview. Question was sort the array based on repeat char count.

Question : [‘#’,’$’,’#’,’?’,’?’,’#’,’#’,’#’] Output : [#,#,#,#,#,?,?,$]

So i try to wrote a solution and it is working as expected. Please see my solution in comment and let me know if scope of optimization available.

Please let me know if any suggestions or concerns

Answer

Well, how about

q = ['#','$','#','?','?','#','#','#']

a = q
    .sort()
    .join('')
    .match(/(.)1*/g)
    .sort((x, y) => y.length - x.length)
    .join('')
    .split('')

console.log(...a)

Leave a Reply

Your email address will not be published. Required fields are marked *