Created
December 10, 2015 22:15
-
-
Save joePichardo/0bd618a97aedf8fa4b54 to your computer and use it in GitHub Desktop.
Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. For example, where([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).
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
// Bonfire: Where do I belong | |
// Author: @joepichardo | |
// Challenge: http://www.freecodecamp.com/challenges/bonfire-where-do-i-belong | |
// Learn to Code at Free Code Camp (www.freecodecamp.com) | |
function where(arr, num) { | |
// Find my place in this sorted array. | |
var indexOfNum; | |
//sort from lowest to highest | |
arr.sort(function(a, b) { | |
return a - b; | |
}); | |
//go through sorted array | |
//find if num and variable in array are equal, return same index | |
// else if arr variable is less than number continue | |
// to add 1 to the current index to place it in front of lower variable | |
for(var i = 0; i < arr.length ; i ++){ | |
if(num === arr[i]){ | |
indexOfNum = i; | |
}else if (arr[i] < num){ | |
indexOfNum = i+1; | |
} | |
} | |
return indexOfNum; | |
} | |
where([40, 60], 50); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment