简体   繁体   English

如何使用javascript查找数组中的最小十进制值

[英]How to find minimum decimal value in array using javascript

I have array with decimal nos such as 我有十进制数的数组,如

  var idArray = ["98.40", "111.46", "144.47", "180.48", "217.49", "284.50", "424.51", "571.52", "1887.53", "1960.54", "1972.55", "2118.56", "2167.57", "2467.58", "2480.59", "2488.60", "2662.61", "2671.62", "2767.63", "2982.64", "3168.65", "3263.66", "3295.67", "3369.68", "3579.69", "3592.70", "3600.71", "3605.72", "3620.73", "3646.74", "3852.75", "3857.76", "4031.77", "4489.78", "4975.79"]

I found the minimum value in the array as below 我在数组中找到了最小值,如下所示

var result = Math.min.apply(null, idArray ); var result = Math.min.apply(null,idArray);

I got result as 98.4 我的结果为98.4

Is there a way to return actual value in the array as 98.40 有没有办法将数组中的实际值返回为98.40

If it really is an array, you can do it the old fashion way with iteration instead, and return the actual string instead of the parsed number, that way number of decimals is not important. 如果它确实是一个数组,你可以用旧方式代替迭代,并返回实际的字符串而不是解析的数字,这样小数位数就不重要了。

 var idArray = ["98.40", "111.46", "144.47", "180.48", "217.49", "284.50", "424.51", "571.52", "1887.53", "1960.54", "1972.55", "2118.56", "2167.57", "2467.58", "2480.59", "2488.60", "2662.61", "2671.62", "2767.63", "2982.64", "3168.65", "3263.66", "3295.67", "3369.68", "3579.69", "3592.70", "3600.71", "3605.72", "3620.73", "3646.74", "3852.75", "3857.76", "4031.77", "4489.78", "4975.79"]; var result = idArray[0]; idArray.forEach(function(x) { if (parseFloat(x) < result) result = x; // find smallest number as string instead }); document.body.innerHTML = result; 

or, you could just sort the array and get the first item (I sliced it to not modify the original) 或者,您可以只对数组进行排序并获取第一个项目(我将其切成不修改原始项目)

var result = idArray.slice().sort(function(a,b) {
    return a - b;
}).shift();

or, use Array.reduce 或者,使用Array.reduce

var result = idArray.reduce(function (a,b) {
    return parseFloat(a) < parseFloat(b) ? a : b;
});

You could code your own: 你可以编写自己的代码:

minInArr = function(arr) {
    var smallest = arr[0];

    for(var i=1; i<arr.length; i++){
        if(parseInt(arr[i],10) < smallest){
            smallest = arr[i];   
        }
    }

    return smallest
}

Made this code based on this one: Return index of greatest value in an array 基于此代码制作此代码: 返回数组中最大值的索引

There are a couple of methods in addition to those already here (though one is pretty similar to adeneo's). 除了那些已经存在的方法之外还有几种方法(尽管一种方法与adeneo非常相似)。 One is to copy the array, sort it, then get the 0 index value: 一种是复制数组,对其进行排序,然后获取0索引值:

var min = idArray.slice().sort(function(a,b){return a - b})[0];

If you don't care about sorting the original array, drop the .slice() part. 如果您不关心对原始数组进行排序,请删除.slice()部分。

Another way is to use Math.min to get the value, then use some to find it in the original array. 另一种方法是使用Math.min获取值,然后使用一些在原始数组中找到它。 The benefit of some is that it will stop at the first match: 一些人的好处是它将在第一场比赛时停止:

var min, temp = Math.min.apply(Math, idArray);

idArray.some(function(v){ return temp == v? min = v : false});

console.log(min);

There are pros and cons to each, choose whatever is easiest to maintain. 每个人都有利弊,选择最容易维护的东西。

尝试:

var roundedResult = parseFloat(result).toFixed(2);

The trailing zero has no importance and hence it is truncated. 尾随零没有重要性,因此它被截断。 So you have no other go other than storing it as a string. 所以除了将其存储为字符串之外,别无其他。

var result = Math.min.apply(null, idArray);
result = (result+"").test(/\.\d\d$/) ? result : result + "0"

Applying Math.min will always coerce your answer to a number, if you coerce it back to a string you loose any trailing zeros. 应用Math.min将始终强制您对数字的回答,如果您将其强制回字符串,则会丢失任何尾随零。 As others have suggested if you know you will always have a fixed number of digits after the decimal you could use .toFixed . 正如其他人所建议的那样,如果你知道你在小数点后总是有一个固定的位数,你可以使用.toFixed

A better solution that doesn't rely on having a fixed number of decimal points would be to use .reduce : 不依赖于具有固定数量的小数点的更好的解决方案是使用.reduce

var result,
  idArray = ["98.40", "111.46", "144.47", "180.48", "217.49", "284.50", "424.51", "571.52", "1887.53", "1960.54", "1972.55", "2118.56", "2167.57", "2467.58", "2480.59", "2488.60", "2662.61", "2671.62", "2767.63", "2982.64", "3168.65", "3263.66", "3295.67", "3369.68", "3579.69", "3592.70", "3600.71", "3605.72", "3620.73", "3646.74", "3852.75", "3857.76", "4031.77", "4489.78", "4975.79"];

result = idArray.reduce(function (prev, cur) {
  if (+prev < +cur) {
    return prev;
  } else {
    return cur;
  }
 });

console.log(result); // "98.40"

A quick explanation of what this does: 快速解释这是做什么的:

  • .reduce iterates over the array and calls the provided function once for each item in the array. .reduce遍历数组并为数组中的每个项调用提供的函数一次。
  • This code just uses the first two parameters available in the function, but there are a couple of others available too . 此代码仅使用函数中可用的前两个参数,但也有其他几个可用 The first parameter is the value returned from the previous call ( prev , which will be undefined on the first call). 第一个参数是从前一个调用返回的值( prev ,在第一次调用时将是undefined的)。 The second parameter will be the value of the current item in the array ( cur ). 第二个参数是数组中当前项的值( cur )。
  • Before comparing the the two they are each coerced from strings to numbers using the Unary plus operator . 在比较两者之前,使用Unary plus运算符将它们从字符串强制转换为数字。
  • If prev is smaller it is returned and the next time the function runs prev will be the same, otherwise cur is returned and become the new value of prev on the next call. 如果prev较小则返回,并且下次函数运行prev将相同,否则返回cur并在下一次调用时成为prev的新值。 It is important to note that when the variables were coerced to compare them that just changed the values being compared in the conditional statement, it did not change the actual value stored in the variable, it remains a string. 重要的是要注意,当变量被强制比较它们只是改变条件语句中比较的值时,它没有改变存储在变量中的实际值,它仍然是一个字符串。
  • After the function has been called on the last item in the array the final value of prev is returned and stored in result . 在对数组中的最后一项调用函数之后,返回prev的最终值并将其存储在result

You could shorten it a little using a ternary statement : 您可以使用三元语句将其缩短一点:

result = idArray.reduce(function (prev, cur) {
  return +prev < +cur ? prev : cur;
 });

If you aren't afraid to use ES6 syntax (not all browsers currently support it) you could make it even shorter with a arrow function : 如果您不害怕使用ES6语法(并非所有浏览器目前都支持它),您可以使用箭头功能缩短它:

result = idArray.reduce((prev, cur) => +prev < +cur ? prev : cur);

The one potential (but unlikely) problem with this approach is that it coerces prev every time it makes a comparison. 这种方法的一个潜在(但不太可能)的问题是它每次进行比较时都会强制使用prev This adds a tiny bit of overhead to each step in the loop. 这为循环中的每个步骤增加了一点点开销。 If performance is a concern it would be better to get away from trying to do it with a one-liner and write a function to do it: 如果性能是一个问题,那么最好不要尝试使用单行程序并编写一个函数来执行此操作:

var arrayMin = function  (arr) {
  var i,
    len,
    prev, // prev and cur will hold numbers that are coerced from strings
    cur,  // once when they are first encountered
    minIndex; // keep track of the index of the smallest item rather
              // than copying a string every time we find a smaller number

  prev = +arr[0];
  minIndex = 0;
  for (i = 1, len = arr.length; i < len; i += 1) {
    cur = +arr[i];
    if (cur < prev) {
      prev = cur;
      minIndex = i;
    }
  }

  return arr[minIndex];
};

var result = arrayMin(idArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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