[Solved] Javascript sorting string [closed]


I think, this is not a sorting but a generation of a new array that accomplish your output, in that case, you could do something like this:

1) First filter all A and all B on different arrays.

2) Then create a new array where progressively you put two elements (or the quantity available) of each of the previous filtered arrays.

const input = ['A', 'B', 'A', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'A'];

let arrA = input.filter(x => x === 'A');
let arrB = input.filter(x => x === 'B');
let res = [];

for (let i = 0; i < Math.max(arrA.length, arrB.length); i += 2)
{
    res.push(...arrA.slice(i, i + 2), ...arrB.slice(i, i + 2));
}

console.log(JSON.stringify(res));

In the case you need a more generic approach, you can use next one, or take the answer made by Nina Scholz

const input = ['D', 'A', 'B', 'C', 'A', 'A', 'B', 'A', 'B', 'D', 'A', 'B', 'A', 'B', 'A', 'A', 'C', 'D', 'D', 'D'];

let groups = input.sort().reduce(
    (acc, curr) => {
        acc[curr] = [...(acc[curr] || []), curr];
        return acc;
    },
    {}
);

let maxLength = Math.max(...Object.values(groups).map(group => group.length));

let res = [];

for (let i = 0; i < maxLength; i += 2)
{
    Object.values(groups).forEach(
        group => res.push(...group.slice(i, i + 2))
    );
}

console.log(res);

0

solved Javascript sorting string [closed]