Reputation: 71
I have group of numbers. Without using methods, how to pick the index of the smallest number in JavaScript? Explain, how the code will work.
let numbers = [20, 90, 10, 324, 9, 73] //Example array of numbers.
Upvotes: 0
Views: 1340
Reputation: 1658
Barebones, without methods:
let numbers = [20, 90, 10, 324, 9, 73]
let smallest = 0
for (i in numbers) {
if (numbers[smallest] > numbers[i]) smallest = i
}
console.log(smallest)
First, we make a variable "smallest" and set it to 0, which is the first index of the array. Then, we go through the entire array and see if there's a number smaller than numbers[smallest]
, the initial value of which is 0. If there is, each time smallest
is set to the index of that smaller number.
By the end of the array, we have the variable smallest
set to the index of the smallest number in the array. That's the solution without methods.
Using array methods and the Math library:
let numbers = [20, 90, 10, 324, 9, 73]
let smallest = numbers.indexOf(Math.min(...numbers))
console.log(smallest)
Math.min()
takes a list of numbers and returns the smallest....numbers
is what's called "spreading". Math.min()
takes parameters, not an array, (Math.min(1, 2, 3)
not Math.min([1, 2, 3]
). So ...numbers
turns [20, 90, 10, 324, 9, 73]
into (20, 90, 10, 324, 9, 73)
.indexOf()
method takes a value and finds the index of that value in an array.Upvotes: 3
Reputation: 76
You can get the smallest number first
let numbers = [20, 90, 10, 324, 9, 73];
let smallest = Math.min(...numbers);
Then, you can get its index easily using the indexOf function.
let index = numbers.indexOf(smallest);
Upvotes: 0