Custom Sorting Javascript with A-Z set

44 views Asked by At

I have an array which is

[
  'B. Wound Bed',
  'A. Wound Location and Measurements',
  'D. Drainage',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'Haroon Question Group Without Show PCP',
  'D. Drainage',
  'Haroon Question Group With Show PCP',
  'A. Wound Location and Measurements',
  'C. Surrounding Tissue',
];

i want to sort it in such a way that it should return like this

[
  'A. Wound Location and Measurements',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'D. Drainage',
  'A. Wound Location and Measurements',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'D. Drainage',
  'Haroon Question Group With Show PCP',
  'Haroon Question Group Without Show PCP'
]

It should complete the whole A-Z set and then start again from A-Z

I have tried this one but it doesn't give the desired result

  'B. Wound Bed',
  'A. Wound Location and Measurements',
  'D. Drainage',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'Haroon Question Group Without Show PCP',
  'D. Drainage',
  'Haroon Question Group With Show PCP',
  'A. Wound Location and Measurements',
  'C. Surrounding Tissue',
];

arr.sort((a, b) => {
    let aIndex = parseInt(a.charAt(0), 36);
    let bIndex = parseInt(b.charAt(0), 36);
    
    if (aIndex < bIndex) return -1;
    if (aIndex > bIndex) return 1;
    
    return 0;
});

console.log(arr);

it returns something like this


"A. Wound Location and Measurements", 
"A. Wound Location and Measurements",
"B. Wound Bed",
"B. Wound Bed",
"C. Surrounding Tissue",
"C. Surrounding Tissue",
"D. Drainage",
"D. Drainage",
"Haroon Question Group Without Show PCP",
"Haroon Question Group With Show PCP"
1

There are 1 answers

0
trincot On BEST ANSWER

You could distribute the entries over buckets, where there is a bucket for each letter (A-Z) and a catch-all bucket for all other entries.

Then consume these buckets in a cyclic way to populate the result array:

const data = [
  'B. Wound Bed',
  'A. Wound Location and Measurements',
  'D. Drainage',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'Haroon Question Group Without Show PCP',
  'D. Drainage',
  'Haroon Question Group With Show PCP',
  'A. Wound Location and Measurements',
  'C. Surrounding Tissue',
];


// Split the entries in their buckets based on the starting letter:
let buckets = Array.from({length: 27}, () => []);
for (const s of data) {
    buckets[/^[A-Z]\./.test(s) ? s.charCodeAt() - 65 : 26].push(s);
}
// The last bucket is a catch-all for elements that do not match the pattern
const last = buckets.pop();

// Consume the buckets one by one in cyclic order until we have all of them
const sorted = [];
while (buckets.length) {
    buckets = buckets.filter(arr => arr.length);
    for (const bucket of buckets) {
        sorted.push(bucket.shift());
    }
}
sorted.push(...last); // Add the unsorted entries
console.log(sorted);