Search code examples
javascriptalgorithmsortingcounting-sortnumber-with-delimiter

JS Counting Sort with Delimiter


I have a sample of my data with the following array that's currently in the order the result should look like; how would I implement a counting sort to keep this data organized in this form:

  1. Organized by the first 4 digits in ascending order.

  2. Organized by the last 4 digits after the "-" delimiter in a ascending order.

  3. Check for digits after the ":" delimiter and organize in ascending order

    array = [5080-2002,5080-2002:01,5080-2002:02,5080-2102,5080-2102:01,5080-2103,5080-2103:01,5460-1601,5460-1601:01,5460-1601:02]

This is way beyond my current level of experience, so any help would be greatly appreciated!

Thank you!!


Solution

  • Three assumptions here:

    • - is always a part of an element
    • : is optional (and element having this should always follow the one with that part empty)
    • the number of digits in each part is not fixed (otherwise it'll be just a case for sort(), as in @NinaScholz answer)

    For those, here's one possible way:

    const arr = [
      '111-111:111',
      '111-111',
      '111-111:22',
      '111-22',
      '111-22:111',
      '111-22:22',
      '22-111:111',
      '22-111:22',
      '22-111',
      '22-22',
      '22-22:111',
      '22-22:22',
    ]
    
    arr.sort((a, b) => {
      const [a0, a1, a2 = -Infinity] = a.split(/[-:]/);
      const [b0, b1, b2 = -Infinity] = b.split(/[-:]/);
      return a0 - b0 || a1 - b1 || a2 - b2;
    })
    
    console.log(arr);