jquery Tablesorter - natural sort order? - javascript

I've looked through all the answers listed for tablesorter but can't find what I'm looking for.
I have a table which I'm trying to sort, one column contains product model numbers which include both letters and numbers, the problem is that it sorts alphabetically but not with the numbers in their proper order. For example the sorted column comes out like this:
STRB 18,
STRB 19,
STRB 2,
STRB 20,
STRB 23 - you get the idea.
I've gathered that I need this column to sort in natural order, but I've not got any js chops to do this with. If anybody could point me in the right direction I would be very grateful!

taken from some old code of mine
compare = {
natural: function(a, b) {
function prepare(s) {
var q = [];
s.replace(/(\D)|(\d+)/g, function($0, $1, $2) {
q.push($1 ? 1 : 2);
q.push($1 ? $1.charCodeAt(0) : Number($2) + 1)
});
q.push(0);
return q;
}
var aa = prepare(a), bb = prepare(b), i = 0;
do {
if(aa[i] != bb[i])
return aa[i] - bb[i];
} while(aa[i++] > 0);
return 0;
}
}
example of use
test = ['img100b', 'img21', 'img18', 'img100a', 'img1', 'img2']
console.log(test.sort(compare.natural))

The jquery tablesorter plugin offers the ability to write your own parser.
Check out the example and give it a shot!
http://tablesorter.com/docs/example-parsers.html

Not sure what you mean by "natrual" order, but I am guessing you mean that strb 2 would be before strb 18.
The order you have above is correct for strings. if you want to sort by the number portion (assuming all the strb's are always the same) you will have to do a substring to get the number only and then sort the data.
I would also NOT do this in javascript. Let your database work for you and let it handle the order of the data. It will save you a lot of pain.

Related

Sort a list by the second number after a dot

I need to sort a list by the second batch number with JavaScript.
This is how it looks like now:
1101.19
1201.17
1301.09
What I need is:
1301.09
1201.17
1101.19
As I am still learning to program I can't figure out the issue. But need it at work.
Can someone help me understand the process of how to do it?
Sort the array depending on the decimal part. Here is the solution
Sort the array by selecting the decimal part of the number inside the sort function.
You can get the decimal part of any number by taking modulus operation with 0.1. Link.
const arr = [1101.19, 1201.17, 1301.09, 1201.20];
arr.sort((a, b) => {return (a % 1 - b % 1)});
console.log(arr);
You need to split each element before sort and compare second parts
let array = ["1101.69", "1701.57", "1301.09"];
array.sort((a,b)=>{
let pair1 = a.split('.');
let pair2 = b.split('.');
return ( parseInt(pair1[1]) < parseInt(pair2[1])) ? -1 : 1;
});
console.log(array);

Splitting an alphanumeric character to sort and then concatenating back in javascript

I'm trying to sort a bunch of alphanumeric characters that look like this:
[AD850X, MP342X, OP452X, ZC234X, ZC540X]
The sorting should be based off only numbers, so I have to remove all alpha characters from this code and then I want to add those characters back after I sort them for the purposes of my code as they were before. For example, the above string should first look like this:
[850, 342, 452, 234, 540]
Then this,
[234, 342, 452, 540, 850]
And then finally this,
[ZC234X, MP342X, OP452X, ZC540X, AD850X]
I've been thinking about how to do this and I'm not sure how I would get the same two letters in the front to reattach to the numeric code after sorting (the last character, in this case "X,"would always be the same and I would concatenate this value after adding the first two alpha characters as they were before.
If anyone could help me out with this I would greatly appreciate it.
Thanks!
EDIT: One other question, once this runs, I want to only output the low and high value of the array (which can have different number of elements). I tried using .min and .max but not sure how to do that with the array that logs after you sort. So in the case above I would just need "ZC234X" and "AD850X".
You can use object as hash table to store element and its number and then sort by values form that object.
var data = ['AD850X', 'MP342X', 'OP452X', 'ZC234X', 'ZC540X'];
var obj = {}
data.forEach(e => obj[e] = e.match(/\d+/)[0])
var result = data.sort((a, b) => obj[a] - obj[b]);
console.log(result)
Instead of complicating it by removing the two first letters and then sorting, you could just sort the array comparing only the matched numbers inside each element.
var arr = ['AD850X', 'MP342X', 'OP452X', 'ZC234X', 'ZC540X'],
res = arr.sort((a,b) => a.match(/\d+/)[0] - b.match(/\d+/)[0]),
min = res[0],
max = res[res.length-1];
console.log("min value: " + min + " | max value: " + max);
You could use just the matched nummerical values for sorting. Array#sort works in situ.
This proposal uses a default value, if the regular expression does not match a number.
var array = ['AD850X', 'MP342X', 'OP452X', 'ZC234X', 'ZC540X'];
array.sort((a, b) => (a.match(/\d+/) || 0) - (b.match(/\d+/) || 0));
console.log('min value', array[0]);
console.log('max value', array[array.length - 1]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sorting Javascript array with strings and numbers

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.
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"));
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
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.
JSFiddle Demo
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);
};

sort table alphanumerically with js

I'm trying to modify sorttable.js to add the option to sort alphanumerically.
Right now, if you sort by alpha, strings with numbers in them will sort like this:
String 1
String 10
String 100
String 2
If I make it sort numeric, it ignores the alpha characters when sorting. I'm trying to figure out how to combine the two functions to make it sort by both at once. Here are the two functions:
sort_numeric: function(a,b) {
aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
if (isNaN(aa)) aa = 0;
bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
if (isNaN(bb)) bb = 0;
return aa-bb;
},
sort_alpha: function(a,b) {
if (a[0]==b[0]) return 0;
if (a[0]<b[0]) return -1;
return 1;
},
Could anybody provide any pointers on how I might begin?
in you function, get the 2 numbers. convert them to strings. figure out which is the longest. add "leading zeros" to the other one, then sort alpha as usual.

JavaScript: check if an array is a subsequence of another array (write a faster naïve string search algo)

[5, 4, 4, 6].indexOfArray([4, 6]) // 2
['foo', 'bar', 'baz'].indexOfArray(['foo', 'baz']) // -1
I came up with this:
Array.prototype.indexOfArray = function(array) {
var m = array.length;
var found;
var index;
var prevIndex = 0;
while ((index = this.indexOf(array[0], prevIndex)) != -1) {
found = true;
for (var i = 1; i < m; i++) {
if (this[index + i] != array[i]) {
found = false;
}
}
if (found) {
return index;
}
prevIndex = index + 1
}
return index;
};
Later I have find wikipedia calls it Naïve string search:
In the normal case, we only have to look at one or two characters for each wrong position to see that it is a wrong position, so in the average case, this takes O(n + m) steps, where n is the length of the haystack and m is the length of the needle; but in the worst case, searching for a string like "aaaab" in a string like "aaaaaaaaab", it takes O(nm) steps.
Can someone write a faster indexOfArray method in JavaScript?
The algorithm you want is the KMP algorithm (http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) used to find the starting index of a substring within a string -- you can do exactly the same thing for an array.
I couldn't find a javascript implementation, but here are implementations in other languages http://en.wikibooks.org/wiki/Algorithm_implementation/String_searching/Knuth-Morris-Pratt_pattern_matcher -- it shouldn't be hard to convert one to js.
FWIW: I found this article a good read Efficient substring searching It discusses several variants of Boyer-Moore although it's not in JavaScript. The Boyer-Moore-Horspool variant (by Timo Raita’s -- see first link for link) was going to be my "suggestion" for a potential practical speed gain (does not reduce big-O though -- big-O is upper limit only!). Pay attention to the Conclusion at the bottom of the article and the benchmarks above.
I'm mainly trying to put up opposition for the Knuth-Morris-Pratt implementation ;-)

Categories