Sort an array of JavaScript / JSON objects

//Function to sort an array consisting of Javascript objects by a field you specify

Array.prototype.sortByField = function( fieldName:String, reverse:boolean ) {
	
	var values = this;
	var fieldA, fieldB;
	
	function lowerCaseSort( a, b ){

		fieldA = a[fieldName];
		fieldB = b[fieldName];
		
		if (fieldA=="" && fieldB=="") { 
			return 0;
		} else if (fieldA=="") { 
			return 1;
		} else if (fieldB=="") { 
			return -1; 
		}
		
		fieldA = fieldA.toLowerCase();
		fieldB = fieldB.toLowerCase();
		
		if( fieldA > fieldB ){ return 1 * multiplier; }
		if( fieldA < fieldB ){ return -1 * multiplier; }
		return 0;
	}
	
	function compareToSort(a,b) {
		fieldA = a[fieldName];
		fieldB = b[fieldName];
		
		if (fieldA==null && fieldB==null) { 
			return 0;
		} else if (fieldA==null) { 
			return 1;
		} else if (fieldB==null) { 
			return -1; 
		}
		
		return ( fieldA.compareTo(fieldB) * multiplier);
	}
	function genericSort( a, b ){
		
		fieldA = a[fieldName];
		fieldB = b[fieldName];
		
		if (fieldA==null && fieldB==null) { 
			return 0;
		} else if (fieldA==null) { 
			return 1;
		} else if (fieldB==null) { 
			return -1; 
		}
		
		if( fieldA > fieldB ){ return 1 * multiplier; }
		if( fieldA < fieldB ){ return -1 * multiplier; }
		return 0;
	}
	
	try {
		if( !fieldName || values.length === 0 ){ return values; }
		
		var multiplier = ( reverse ? -1 : 1);
		
		//determine datatype of the fields - based on first value
		//this function can handle string, number and date sorting
		var first = values[0][fieldName];		//string, number or object
		
		var sortFunction;
		if (typeof first == "string") {
			sortFunction = lowerCaseSort;
		} else if (typeof first=="object" && (first.constructor == (new Date).constructor)) {
			sortFunction = compareToSort;
		} else {		//numbers
			sortFunction = genericSort;
		}
		
		values.sort(sortFunction);
		
	} catch (e) {
		print("error while sorting: " + e.toString())
	}
	
	return values;
}





Add this function to a generic SSJS library and you can sort arrays containing JavaScript objects. You can specify by which field the objects should be sorted and if the sort order should be reversed (defaults to false). The function can handle strings (case insensitive), numbers and dates. Empty/ null values are always positioned at the end of the array.

Sample:

var myObjectArray = [
{ nr : 24, name : "Mark" },
{ nr : 18, name : "Pete" },
{ nr : 7, name : "Fred" }
];

//sort by name, ascending
myObjectArray.sortByField("name");

//sort by nr, ascending
myObjectArray.sortByField("nr");

//sort by nr, descending
myObjectArray.sortByField("nr", true);

JavaScript (Server)
Mark Leusink
December 9, 2011 9:24 AM
Rating
284

All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.



No comments yetLogin first to comment...