Suppose, we have an array of strings like this −
const arr = [ '.0', '.1', '.2', '.4', '.2.1', '.3', '.4.1', '.5', '.5.1.5' ];
We are required to write a JavaScript function that takes in one such array. Our function should simply sort the array in increasing order (as seen by a layman).
This means that strings with '.0', followed by '.1's, followed by '.2's, and so on. Therefore, after being sorted, the array should look like −
const output = [ '.0', '.1', '.2.1', '.2, '.3', '.4', '.4.1', '.5', '.5.1.5' ];
Example
The code for this will be −
const arr = [ '.0', '.1', '.2', '.4', '.2.1', '.3', '.4.1', '.5', '.5.1.5' ];
const compare = (a, b) => {
if (a === b) {
return 0
};
const aArr = a.split("."), bArr = b.split(".");
for (let i = 0; i < Math.min(aArr.length, bArr.length); i++) {
if (parseInt(aArr[i]) < parseInt(bArr[i])) {
return -1
};
if (parseInt(aArr[i]) > parseInt(bArr[i])) {
return 1
};
}
if (aArr.length < bArr.length) {
return -1
};
if (aArr.length > bArr.length) {
return 1
};
return 0;
};
arr.sort(compare);
console.log(arr);Output
And the output in the console will be −
[ '.0', '.1', '.2', '.2.1', '.3', '.4', '.4.1', '.5', '.5.1.5' ]