How do i sort an array based on one of its contents
i have an array that contains text and html. myarray[1] contains the following.. myarray[2] contains the same thing just different name 'john' and so on
153); color: white; cursor: pointer; font-size: 12px; font-weight: normal; font-family:
Arial;" onmouseover="this.style.backgroundColor = 'white'; this.style.color='#336699'"
onmouseout="this.style.backgroundColor = ''; this.style.color = 'white'; "
onclick="if(top.mail.checkDataset()) mail.execFunction('javascript: changeMain(\'orderCreate1.do\')')">
<img alt="" src="images/round-white-bullet.gif" height="10" width="10"> John<br>
how ca开发者_高级运维n i sort the whole array so that it ignores everything and sortsd by the name 'john' in this case? the names always come after the image and before the br
if that helps
I have used the sortBy() function from underscore.js to sort arrays and it worked OK for me: http://documentcloud.github.com/underscore/#sortBy
If Matthias Benkard's answer doesn't solve your problem, check out underscore.js
The problem statement is a bit vague, but in general, you can sort an array using some function that extracts the key to be sorted on (I'll call this function key
here) by using something like the following:
array.sort(function(x, y) {
var x_key = key(x);
var y_key = key(y);
return (x_key < y_key ? -1 : x_key === y_key ? 0 : 1);
});
In your case, key
would have to be a function that extracts the name from an array element.
If your array elements are strings, you might want to try regular expressions:
var key = function(x) {
return /<img[^>]*>([^<]*)<br>/.exec(x)[1];
};
精彩评论