简体   繁体   中英

Finding the min index in the array javascript

var myArray = [];
let maxNum = 15;



function findMin(A, start, end){

  var result = Math.min.apply(null, myArray)
  console.log(result)

  return 0;
}

This function should find the index for the minimum value in Array A looking at all values starting at the index start and ending at the index end. This INCLUDES the numbers at start and end.

return the INDEX where the minimum occurs.

For example, if A = [3,2,1,6,4] findMax(A, 0,4) should return 2 since the minimum value is 1 and it occurs at position 2 in this array.

How would I got about finding the index of the minimum number?

(myArray randomly generates numbers in an array already, I just don't know how to find the index of the lowest number in the array)

You could use indexOf() of your minimum value. Or you manually iterate through the array with forEach and remember both the minimum value and it's index.

Array prototype indexOf returns the first index of a value in the array. First, you need to find the minimum value that is between the start index and the end index. That's why we used slice which returns a subarray.

Example of array slice .

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(1, 3));
// slice will return the items from index 1 to upto 3
// expected output: Array ["bison", "camel"] 

Then all we have to do is to find the min value and return the indexOf .

function findMin(A, start, end){
  let minValue = Math.min.apply(A.slice(start, end))
  return A.indexOf(Math.min.apply(Math, A));
}

let A = [3,2,1,6,4]
console.log( findMin( A, 0, 4) )

We can also express the same function using the ES6 arrow function.

const findMin = (A, start, end) => A.indexOf(Math.min.apply(Math, A))

let A = [3,2,1,6,4]
console.log( findMin( A, 0, 4) )

There are two methods: - manual & js functions

  1. JS Function:

    return A.indexOf(Math.min.apply(Math, A));

  2. Manual:

    A loop through he array will be faster any time.

不同JS函数的运行时间

try this way.

let myArray = [5,3,4,1,9];
let maxNum = 15;

function findMin(A, start, end){

  let result = Math.min.apply(null, myArray)
  console.log(myArray.indexOf(result))
}

findMin(myArray, 0, myArray.length)

you can use a combination of Math.min and spread syntax

const arr = [3,2,1,6,4]
const index = arr.indexOf(Math.min(...arr))

console.log(index) // 2

Is this something you are looking for

var ary = [1,6,8,2,0,8,9]
 function findMin(A, start, end) {
   var finalAry = A.slice(start, end);
   var result = Math.min.apply(null, finalAry)
   return A.indexOf(result);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM