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;
}
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...