Reputation: 2587
I have a list of elements in an array in Javascript as follows:
myArray = ["Datastore one - free space 34.23GB", "Datastore two - free space 56.23GB",...]
and so on. I would like to sort the array on the freespace, so in the example above Datastore two would be the first element in the array. The array is always constructed with "- free space xx.xxGB", but the free space could be 5 digits in some cases, so xxx.xxGB for example.
Can anyone help provide a way of sorting the array please? I see I can use something like
"*- free space\s[1-9][0-9]*GB"
So would this be like
myArray.sort("*- free space\s[1-9][0-9]*GB") ?
Is this correct or how would I do this? Many thanks in advance.
Upvotes: 0
Views: 109
Reputation: 3080
This should work as well if you just want the numbers returned.
I split the string by spaces and grab the last section. (#GB), I then grab the substring of everything but the last two characters (so I chop off the GB), I then use the Javascript function to sort the remaining numbers.
window.onload = function() {
myArray = ["Datastore one - free space 34.23GB", "Datastore two - free space 56.23GB", "Datastore two - free space 16.23GB", "Datastore two - free space 6.23GB"];
for (i = 0; i < myArray.length; i++)
{
var output = myArray[i].split(" ").pop();
output = output.substring(0, output.length-2);
myArray[i] = output;
}
myArray.sort(function(a, b){return a-b});
alert(myArray);
};
Upvotes: 1
Reputation: 36438
Pull the numeric parts out in a custom sort function, and subtract:
myArray = ["Datastore one - free space 34.23GB", "Datastore two - free space 56.23GB", "Datastore three - free space 6.23GB" ];
var re = /([0-9\.]+)GB/; // regex to retrieve the GB values
myArray = myArray.sort(
function(a, b) {
var ma = a.match(re); // grab GB value from each string
var mb = b.match(re); // the result is an array, with the number at pos [1]
return (ma[1] - mb[1]);
}
);
alert(myArray.join("\r\n"));
Upvotes: 2
Reputation: 36511
This should do the trick:
myArray.sort(function compare(a, b) {
var size1 = parseFloat(a.replace(/[^0-9\.]/g, ''));
var size2 = parseFloat(b.replace(/[^0-9\.]/g, ''));
if (size1 < size2) {
return -1;
} else if (size1 > size2) {
return 1;
}
return 0;
});
Array.prototype.sort
does not accept a regex, it accepts a callback or will do its best to sort your array based on numeric/alphabetical order if you don't pass a callback
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Upvotes: 1