javascript 数组中最小的数及其位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15455247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Smallest number in array and its position
提问by Ed T.
What I am trying to achieve is to find smallest number in array and its initial position. Here's an example what it should do:
我想要实现的是在数组中找到最小的数字及其初始位置。这是它应该做的一个例子:
temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
So in the end I should know number 3 and position 1. I also had a look here: Obtain smallest value from array in Javascript?, but this way does not give me a number position in the array. Any tips, or code snippets are appreciated.
所以最后我应该知道数字 3 和位置 1。我也看了一下:在 Javascript 中从数组中获取最小值?,但这种方式不会给我数组中的数字位置。任何提示或代码片段表示赞赏。
回答by Guffa
Just loop through the array and look for the lowest number:
只需遍历数组并查找最小的数字:
var index = 0;
var value = temp[0];
for (var i = 1; i < temp.length; i++) {
if (temp[i] < value) {
value = temp[i];
index = i;
}
}
Now value
contains the lowest value, and index
contains the lowest index where there is such a value in the array.
现在value
包含最低值,并index
包含数组中存在此类值的最低索引。
回答by MattDiamant
You want to use indexOf
你想用 indexOf
http://www.w3schools.com/jsref/jsref_indexof_array.asp
http://www.w3schools.com/jsref/jsref_indexof_array.asp
Using the code that you had before, from the other question:
使用您之前的代码,来自另一个问题:
temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
Array.min = function( array ){
return Math.min.apply( Math, array );
};
var value = temp.min;
var key = temp.indexOf(value);
回答by Tony
One-liner:
单线:
alist=[5,6,3,8,2]
idx=alist.indexOf(Math.min.apply(null,alist))
回答by Raku Zeta
See this answerof "find max" version of this question. It is simple and good. You can use the index to get the element afterward.
回答by Eugen Sunic
Here is a solution using simple recursion. The output is an object containing the index position of the min number and the min number itself
这是使用简单递归的解决方案。输出是一个包含最小数字的索引位置和最小数字本身的对象
const findMinIndex = (arr, min, minIndex, i) => {
if (arr.length === i) return {minIndex, min};
if (arr[i] < min) {
min = arr[i]
minIndex = i;
}
return findMinIndex(arr, min, minIndex, ++i)
}
const arr = [5, 5, 22, 11, 6, 7, 9, 22];
const minIndex = findMinIndex(arr, arr[0], 0, 0)
console.log(minIndex);