Home > Net >  JS Counting Sort with Delimiter
JS Counting Sort with Delimiter

Time:06-22

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 me and the research I've done has only helped to the point of sorting without a delimiter. Any help would be greatly appreciated!

Thank you!!

CodePudding user response:

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);

CodePudding user response:

Just sort.

const
    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'];

array.sort();

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related