1

So I am trying to implement a sort function in javascript. I have to implement the "compare" function. The main problem is that I don't know whether the user puts pure numbers, partly numbers or only text in his cell.

Requirement: I dont know which dataformat the user is using in his row

Problem: Following examples after the sort function.

  • Data(pure numbers): 1, 10, 2, 3, ... because it interprets the 10 like "10" which comes before "2".
  • Data(numbers with unit): 1 m, 10 m, 2 m ... same problem, but here I can't simply "try" to parse to double
  • Data(text): test1, test10, test2, ... also wrong sort, not parsable.
  • Data(numbers with commas) 1.3 m, 10.3 m, 2.3 m

Those examples show the data which will be shown wrong. Is the whole column full with text, it works perfect.

Question: Is there a way to compare like that existing in javascript, which will treat numbers as such?

arrayToSort.sort((a, b) => {
    let valueA = a[key];
    let valueB = b[key];
    return valueB < valueA ? -1 : 1;
}
Updater
  • 459
  • 2
  • 13

1 Answers1

1

You could use String#localeCompare with options, which applies a natural sorting.

var data = [1, 10, 2, 3, '1 m', '10 m', '2 m', 'test1', 'test10', 'test2', '1.3 m', '10.3 m', '2.3 m', 10.2, 10.3, 10.4];

data.sort((a, b) => a.toString().localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }))

console.log(data);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • It seems like that's what I searched for. Thanks! I knew there has to be something simple from JavaScript. – Updater Mar 12 '20 at 11:16