Skip to content

Instantly share code, notes, and snippets.

@ArielLeslie
Created December 10, 2015 19:21
Show Gist options
  • Save ArielLeslie/587f889dcec05cf4a9c9 to your computer and use it in GitHub Desktop.
Save ArielLeslie/587f889dcec05cf4a9c9 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). Likewise, where([20,3,5], 19) should return 2 because once the array has been sorted it will lo…
function where(arr, num) {
arr.push(num);
arr = arr.sort(function(a, b) { return a - b; });
return arr.indexOf(num);
}
// Tests
console.log(where([10, 20, 30, 40, 50], 35) + " should be 3");
console.log(where([10, 20, 30, 40, 50], 30) + " should be 2");
console.log(where([40, 60], 50) + " should be 1");
console.log(where([3, 10, 5], 3) + " should be 0");
console.log(where([5, 3, 20, 3], 5) + " should be 2");
console.log(where([2, 20, 10], 19) + " should be 2");
console.log(where([2, 5, 10], 15) + " should be 3");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment