Created
April 25, 2014 12:20
-
-
Save mhuckaby/11287726 to your computer and use it in GitHub Desktop.
find-the-nth-largest-number-in-an-array
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
// http://xorswap.com/questions/167-find-the-nth-largest-number-in-an-array | |
function testData() { | |
return [10, 1001, 15, 7, 33, 1001, 2, 0, 99, 131]; | |
}; | |
function sortAsc(a, b) { | |
if(a < b) { | |
return -1; | |
}else if(a === b) { | |
return 0; | |
}else { | |
return 1; | |
} | |
}; | |
function nthLargest(theArray, n) { | |
if(theArray.length === 1) return theArray[0]; | |
if(theArray.length - 1 < n) return undefined; | |
var sorted = theArray.sort(sortAsc); | |
var i = (theArray.length - 1) - n; | |
return theArray[i]; | |
}; | |
console.log( "testData: " + testData() ); | |
console.log( "sorted testData: " + testData().sort(sortAsc) ); | |
console.log( nthLargest(testData(), 0) ); | |
console.log( nthLargest(testData(), 1) ); | |
console.log( nthLargest(testData(), 2) ); | |
console.log( nthLargest(testData(), 3) ); | |
console.log( nthLargest(testData(), 200) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment