Clever sorting (Sort strings that may or may not contain numbers)

Viewed 93

I need to sort a list of units that may or may not contain a number.

For example ["unit 1", "unit 2", ..., "unit 11"].

Most sorting function will order this: unit 1, unit 11, unit 2..

But I may also have the case that doesn't have a number. ["apt A", "apt B", ..., "apt Z"].

Are there any clever solutions that would sort this correctly:

unit 1, unit 2, ..., unit 11.

apt A, apt B, ..., apt Z.

1 Answers

Given the clarifications in comments, you can split each string by /(\d+)/g and sort by each element in the resulting string array. Treat even indices as strings, and odd indices as numbers:

const input = ['unit 11', 'unit 1', 'unit 2', 'apt 11', 'apt 1', 'apt 2', 'unit A', 'unit c', 'unit B', 'apt a', 'apt C', 'apt b'];

function customSort (a, b) {
  a = a.toUpperCase().split(/(\d+)/g);
  b = b.toUpperCase().split(/(\d+)/g);

  const length = Math.min(a.length, b.length);

  for (let i = 0; i < length; i++) {
    const cmp = (i % 2)
      ? a[i] - b[i]
      : -(a[i] < b[i]) || +(a[i] > b[i]);

    if (cmp) return cmp;
  }

  return a.length - b.length;
}

console.log(input.sort(customSort));

Related