1

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!!

Apalila
  • 53
  • 6

2 Answers2

2

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

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);
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • This is perfect, thank you! I seriously need to work on understanding nested functions better. I didn't know you could "count" backwards from the end of infinity; how does that not break a script? – Apalila Jun 21 '22 at 18:40