Skip to content

Instantly share code, notes, and snippets.

@DForshner
Created May 26, 2014 23:06
Show Gist options
  • Select an option

  • Save DForshner/dd9ae3cb513f69659d74 to your computer and use it in GitHub Desktop.

Select an option

Save DForshner/dd9ae3cb513f69659d74 to your computer and use it in GitHub Desktop.
Find the index of the smallest array element.
// Find the index of the smallest value.
// Linear search
var findIndexOfSmallest = function(arr) {
if (!arr.length) { return -1; }
var lowIdx = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] < arr[lowIdx]) { lowIdx = i; }
}
return lowIdx;
}
console.log(findIndexOfSmallest([]));
console.log(findIndexOfSmallest([90, 100, 30, 20, 70, 40, 50]));
// Reduce intrinsic
var findIndexOfSmallestReduce = function(arr) {
if (!arr.length) { return -1; }
return arr.reduce(function(lowest, next, index) {
return (next < arr[lowest]) ? index : lowest },
0);
}
console.log(findIndexOfSmallestReduce([]));
console.log(findIndexOfSmallestReduce([90, 100, 30, 20, 70, 40, 50]));
// Use Math.min to find smallest element and convert to its index
var findIndexOfSmallestMin = function (arr) {
return arr.indexOf(Math.min.apply(Math, arr));
}
console.log(findIndexOfSmallestMin([]));
console.log(findIndexOfSmallestMin([90, 100, 30, 20, 70, 40, 50]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment