Sorting a FeatureSet by Attribute - JavaScript API

Here is a simple example that shows you how to sort your FeatureSet in the JavaScript API.

The javascript array sort function is actually a very powerful tool. You can pass a function to the sort method that will run each time the items in your array are compared. Since the features in a featureset are stored as an array, you can write your own sort function to sort all the features by an attribute.

Here is the code:

//note: CONDITION is the attribute we are sorting on.
//you will need to change this the appropriate attribute
//a & b are the two features be compared from your array of features

function sortByAttribute(a, b) {
var x = a.attributes.CONDITION.toLowerCase();
var y = b.attributes.CONDITION.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

//call this from within your result function
featureSet.features.sort(sortByFirstName);



Trent Tinker
Developer - ROK Technologies

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Drew's Gravatar Great snippet.. I used this in with the Flex API too!
# Posted By Drew | 1/7/10 10:17 AM
david's Gravatar This just saved me lots and lots of time figuring out a method on my own. Thanks a bunch!
# Posted By david | 5/20/10 12:34 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.002. Contact Blog Owner