Middle
There is an array of strings representing item numbers of a hierarchical numbered list (e.g., '1', '1.1', '1.2', '1.10', '2', '2.1'). How to sort them correctly using the standard sort function with a callback?
sobes.tech AI
Answer from AI
To sort an array of hierarchical numbered strings (for example, '1', '1.1', '1.2', '1.10', '2', '2.1'), you need to compare them by parts separated by dots, as numbers, not as strings. In JavaScript, you can use the sort function with a callback that splits the strings into arrays of numbers and compares them element by element:
const items = ['1', '1.1', '1.2', '1.10', '2', '2.1'];
items.sort((a, b) => {
const aParts = a.split('.').map(Number);
const bParts = b.split('.').map(Number);
const len = Math.max(aParts.length, bParts.length);
for (let i = 0; i < len; i++) {
const aNum = aParts[i] || 0;
const bNum = bParts[i] || 0;
if (aNum !== bNum) {
return aNum - bNum;
}
}
return 0;
});
console.log(items);
// Output: ['1', '1.1', '1.2', '1.10', '2', '2.1']
Thus, the sorting considers the numerical value of each part of the number, not the lexicographical order of strings.