michaelp0730
1/2/2015 - 5:55 PM

Function for sorting an array of mixed values. Taken from JavaScript The Good Parts. The comparison function takes two params and returns 0

Function for sorting an array of mixed values. Taken from JavaScript The Good Parts. The comparison function takes two params and returns 0 if they are equal, a negative number if the first param should come first, and a positive number if the second param should come first. If letter case doesn't need to be specific, you should first convert the strings to lowercase before comparing them.

var m = ['aa', 'bb', 'a', 4, 8, 15, 16, 23, 42];

m.sort(function (a, b) {
	if (a === b) {
		return 0;
	}
	if (typeof a === typeof b) {
		return a < b ? -1 : 1;
	}
	return typeof a < typeof b ? -1 : 1;
});

// m is [4, 8, 15, 16, 23, 42, 'a', 'aa', 'bb']