Simple sanitation/sorting function for javascript

I recently posted a StackOverflow answer I thought I would share on my blog. Full code is included in the included JSFiddle

The question was thus:

I have an array like this with decimal values

["$79.34", "$99.23", "$149", "$139.34", "$379", "$199.00", "$5", "$9", "$14", "$39", "$59", "$24", "$29", "$189", "$10,$20", "$500", "$1", "$4", "$8.66", "$2", "$19", "$18", "$11", "$15", "$40", "$89", "$100", "$400.15", "$30,$119", "$15,$30"]

For my store and I can't figure out how to use javascript to sort them ? The $ (or any symbol for that matter) seems to be causing issues for me ?

How can I solve this ?

The problem here was threefold. First, the data needed to be sanitized to remove values like "$10,$20" into two distinct elements "$10" and "$20". This was accomplished with the following:

//first sanitize the data
for (var i = 0; i {
if (priceStrings[i].toString().search(",") != -1)
{
var splits = priceStrings[i].toString().split(",");
priceStrings.splice(i, 1)
priceStrings = priceStrings.concat(splits);
i--;
}
}

Then, the dollar sign needed to be stripped. Simple enough.

var prices = [];
for (var i = 0; i {
priceStrings[i] = priceStrings[i].toString().replace("$", "");
prices.push(parseFloat(priceStrings[i]));
}

After that, all was left is to sort by numeric value (rather than the lexographical sort array.sort() performs by default in Javascript).

prices.sort(function(a,b){return a - b});

I hope this helps somebody facing a similar problem. I'll continue to write about interesting things I might be working on more often, now that I'm finished with school.

The included JSFiddle, for those who didn't see it at the top

© 2011 Cody Herring. Drupal theme by Kiwi Themes.