简体   繁体   中英

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 );

I got result as 98.4

Is there a way to return actual value in the array as 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

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). One is to copy the array, sort it, then get the 0 index value:

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.

Another way is to use Math.min to get the value, then use some to find it in the original array. 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. As others have suggested if you know you will always have a fixed number of digits after the decimal you could use .toFixed .

A better solution that doesn't rely on having a fixed number of decimal points would be to use .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.
  • 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). The second parameter will be the value of the current item in the array ( cur ).
  • Before comparing the the two they are each coerced from strings to numbers using the Unary plus operator .
  • 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. 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 .

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 :

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. 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);

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