Ordering a string with multiple dots in javascript

Viewed 122

I have this array:

["4.1.0.57", "4.1.0.99", "4.1.0.54", "4.1.0.65", "4.1.0.87", "4.1.0.97", "4.1.0.63", "4.1.0.96", "4.1.0.51", "4.1.0.84", "4.1.0.95", "4.1.0.105", "4.1.0.38", "4.1.0.59", "4.1.0.47", "4.1.0.69", "4.1.0.93", "4.1.0.92", "4.1.0.103", "4.1.0.100", "4.1.0.90"]

I am trying to sort this using lodash:

_.sortBy(keys)
_.orderBy(keys)

["4.1.0.100", "4.1.0.103", "4.1.0.105", "4.1.0.38", "4.1.0.47", "4.1.0.51", "4.1.0.54", "4.1.0.57", "4.1.0.59", "4.1.0.63", "4.1.0.65", "4.1.0.69", "4.1.0.84", "4.1.0.87", "4.1.0.90", "4.1.0.92", "4.1.0.93", "4.1.0.95", "4.1.0.96", "4.1.0.97", "4.1.0.99"]

Its not ordering properly

1 Answers

You could sort with String#localeCompare and options.

var array = ["4.1.0.57", "4.1.0.99", "4.1.0.54", "4.1.0.65", "4.1.0.87", "4.1.0.97", "4.1.0.63", "4.1.0.96", "4.1.0.51", "4.1.0.84", "4.1.0.95", "4.1.0.105", "4.1.0.38", "4.1.0.59", "4.1.0.47", "4.1.0.69", "4.1.0.93", "4.1.0.92", "4.1.0.103", "4.1.0.100", "4.1.0.90"];

array.sort(function (a,b) {
 return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
});

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

Related