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

JS Sort an array into three occurrences

I need to arrange the array so that three are only instances left or less, for example

let tab = [ 3, 3, 4, 4, 5, 4, 5, 6, 6, 4, 6, 3, 7, 7, 3]

I would like to get something like this initially;

let newTab = [3,3,3,4,4,4,5,5,6,6,6,7,7]

I am asking for help because I have no idea anymore.

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

>Solution :

You could group the data by thie value and take only the max length of three items for each group.

As result take the values in a flat array.

const
    tab = [3, 3, 4, 4, 5, 4, 5, 6, 6, 4, 6, 3, 7, 7, 3],
    result = Object
        .values(tab.reduce((r, v) => {
            r[v] ??= [];
            if (r[v].length < 3) r[v].push(v);
            return r;
        }, {}))
        .flat();

console.log(...result);
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