Created
June 5, 2012 07:53
-
-
Save lsauer/2873428 to your computer and use it in GitHub Desktop.
JavaScript is different: Finding the maximum or minimum element in an Array / List + randomization or shuffling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// www.lsauer.com lo sauer 2012 - BSD license | |
// description: several ways of finding the maximum or minimum element in a list | |
// with a demonstration of sorting-functions | |
// tood: add some benchmarks | |
var arr = [1,3,32,432,23,200,-10,30,44,1]; | |
//#1 short version | |
for(var i=0,max=0; i<arr.length; arr[i]>max&&(max=arr[i]),i++); | |
//>432 | |
for(var i=0,min=0; i<arr.length; arr[i]<min&&(min=arr[i]),i++); | |
//>-10 | |
//#2 long version, extending the Array object | |
Array.prototype.max = function() { | |
var i = 0; | |
var _max = this[i]; | |
for( i=0; i < this.length; i++ ) { | |
if( _max < this[i] ) | |
_max = this[i]; | |
} | |
return _max; | |
} | |
//#3 sorting; allows individual sorting algorithm; mutable operation! | |
arr.sort().slice(-1)[0]; //max | |
arr.sort().[arr.length-1]; //max | |
arr.sort().reverse()[0] //max | |
arr.sort().pop(); //max; mutable operation i.e. shortens the array! | |
//>432 | |
arr.sort()[0] | |
//>-10 | |
//By passing a sorting function, we can use it for shuffling the array and other neat | |
//if argument 1 or 'a' is >0 then the argument is moved to a lower index than argument 2 or 'b', and vice versa. | |
//tasks in addition to canonical sorting | |
//sort numerically, ascending | |
arr.sort( function(a,b){return a-b} ); | |
//sort numerically, descening | |
arr.sort( function(a,b){return b-a} ); | |
//sort by first ASCII character value | |
var arr = ['c',1,3,32,432,23,200,'b',-10,30,44,1,'a']; | |
arr.sort( function(a,b){return a.toString().charCodeAt(0) - b.toString().charCodeAt(0)} ) | |
[-10, 1, 1, 200, 23, 3, 32, 30, 432, 44, "a", "b", "c"] | |
//shuffle | |
arr.sort( function(a,b){return .5-Math.random()} ); | |
//#3 via 'apply' | |
var arr = ['c',1,3,32,432,23,200,'b',-10,30,44,1,'a']; | |
Math.max.apply(null,arr.filter(Number)) | |
//>432 | |
Math.min.apply(null,arr.filter(Number)) | |
//>-10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment