Obtain smallest value from array in Javascript?

JavascriptArraysMin

Javascript Problem Overview


Array justPrices has values such as:

[0] = 1.5
[1] = 4.5
[2] = 9.9.

How do I return the smallest value in the array?

Javascript Solutions


Solution 1 - Javascript

The tersest expressive code to find the minimum value is probably rest parameters:

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = Math.min(...arr)
console.log(min)


Rest parameters are essentially a convenient shorthand for Function.prototype.apply when you don't need to change the function's context:

var arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
var min = Math.min.apply(Math, arr)
console.log(min)


This is also a great use case for Array.prototype.reduce:

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = arr.reduce((a, b) => Math.min(a, b))
console.log(min)

It may be tempting to pass Math.min directly to reduce, however the callback receives additional parameters:

callback (accumulator, currentValue, currentIndex, array)

In this particular case it may be a bit verbose. reduce is particularly useful when you have a collection of complex data that you want to aggregate into a single value:

const arr = [{name: 'Location 1', distance: 14}, {name: 'Location 2', distance: 58}, {name: 'Location 3', distance: 20}, {name: 'Location 4', distance: 77}, {name: 'Location 5', distance: 66}, {name: 'Location 6', distance: 82}, {name: 'Location 7', distance: 42}, {name: 'Location 8', distance: 67}, {name: 'Location 9', distance: 42}, {name: 'Location 10', distance: 4}]
const closest = arr.reduce(
  (acc, loc) =>
    acc.distance < loc.distance
      ? acc
      : loc
)
console.log(closest)


And of course you can always use classic iteration:

var arr,
  i,
  l,
  min

arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
min = Number.POSITIVE_INFINITY
for (i = 0, l = arr.length; i < l; i++) {
  min = Math.min(min, arr[i])
}
console.log(min)

...but even classic iteration can get a modern makeover:

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
let min = Number.POSITIVE_INFINITY
for (const value of arr) {
  min = Math.min(min, value)
}
console.log(min)

Solution 2 - Javascript

Jon Resig illustrated in this article how this could be achieved by extending the Array prototype and invoking the underlying Math.min method which unfortunately doesn't take an array but a variable number of arguments:

Array.min = function( array ){
    return Math.min.apply( Math, array );
};

and then:

var minimum = Array.min(array);

Solution 3 - Javascript

I find that the easiest way to return the smallest value of an array is to use the Spread Operator on Math.min() function.

return Math.min(...justPrices);
//returns 1.5 on example given 

The page on MDN helps to understand it better: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min

A little extra: This also works on Math.max() function

return Math.max(...justPrices); //returns 9.9 on example given.

Hope this helps!

Solution 4 - Javascript

Update: use Darin's / John Resig answer, just keep in mind that you dont need to specifiy thisArg for min, so Math.min.apply(null, arr) will work just fine.


or you can just sort the array and get value #1: [2,6,7,4,1].sort()[0]

[!] But without supplying custom number sorting function, this will only work in one, very limited case: positive numbers less than 10. See how it would break:

var a = ['', -0.1, -2, -Infinity, Infinity, 0, 0.01, 2, 2.0, 2.01, 11, 1, 1e-10, NaN];

// correct: 
a.sort( function (a,b) { return a === b ? 0 : a < b ? -1: 1} );
//Array [NaN, -Infinity, -2, -0.1, 0, "", 1e-10, 0.01, 1, 2, 2, 2.01, 11, Infinity]

// incorrect:
a.sort();
//Array ["", -0.1, -2, -Infinity, 0, 0.01, 1, 11, 1e-10, 2, 2, 2.01, Infinity, NaN]

And, also, array is changed in-place, which might not be what you want.

Solution 5 - Javascript

ES6 is the way of the future.

arr.reduce((a, b) => Math.min(a, b));

I prefer this form because it's easily generalized for other use cases

Solution 6 - Javascript

Imagine you have this array:

var arr = [1, 2, 3];

ES6 way:

var min = Math.min(...arr); //min=1

ES5 way:

var min = Math.min.apply(null, arr); //min=1

If you using D3.js, there is a handy function which does the same, but will ignore undefined values and also check the natural order:

> d3.max(array[, accessor]) > > Returns the maximum value in the given array using natural order. If > the array is empty, returns undefined. An optional accessor function > may be specified, which is equivalent to calling array.map(accessor) > before computing the maximum value. > > Unlike the built-in Math.max, this method ignores undefined values; > this is useful for ignoring missing data. In addition, elements are > compared using natural order rather than numeric order. For example, > the maximum of the strings [“20”, “3”] is “3”, while the maximum of > the numbers [20, 3] is 20.

And this is the source code for D3 v4:

export default function(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      max;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  return max;
}

Solution 7 - Javascript

var array =[2,3,1,9,8];
var minvalue = array[0]; 
for (var i = 0; i < array.length; i++) {
	if(array[i]<minvalue)
	{
		minvalue = array[i];
	}
	
}
  console.log(minvalue);

Solution 8 - Javascript

Possibly an easier way?

Let's say justPrices is mixed up in terms of value, so you don't know where the smallest value is.

justPrices[0] = 4.5
justPrices[1] = 9.9
justPrices[2] = 1.5

Use sort.

justPrices.sort();

It would then put them in order for you. (Can also be done alphabetically.) The array then would be put in ascending order.

justPrices[0] = 1.5
justPrices[1] = 4.5
justPrices[2] = 9.9

You can then easily grab by the first index.

justPrices[0]

I find this is a bit more useful than what's proposed above because what if you need the lowest 3 numbers as an example? You can also switch which order they're arranged, more info at http://www.w3schools.com/jsref/jsref_sort.asp

Solution 9 - Javascript

function smallest(){
  if(arguments[0] instanceof Array)
    arguments = arguments[0];

  return Math.min.apply( Math, arguments );
}
function largest(){
  if(arguments[0] instanceof Array)
    arguments = arguments[0];

  return Math.max.apply( Math, arguments );
}
var min = smallest(10, 11, 12, 13);
var max = largest([10, 11, 12, 13]);

console.log("Smallest: "+ min +", Largest: "+ max);

Solution 10 - Javascript

Here’s a variant of Darin Dimitrov’s answer that doesn’t modify the Array prototype:

const applyToArray = (func, array) => func.apply(Math, array)

applyToArray(Math.min, [1,2,3,4]) // 1
applyToArray(Math.max, [1,2,3,4]) // 4

Solution 11 - Javascript

function tinyFriends() {
    let myFriends = ["Mukit", "Ali", "Umor", "sabbir"]
    let smallestFridend = myFriends[0];
    for (i = 0; i < myFriends.length; i++) {
        if (myFriends[i] < smallestFridend) {
            smallestFridend = myFriends[i];
        }
    }
    return smallestFridend   
}

Solution 12 - Javascript

A super-easy way to find the smallest value would be

Array.prototype.min = function(){
    return Math.min.apply(Math,this);
};

To call the function, just use the name of the array and add .min()

Array.prototype.min = function(){
    return Math.min.apply(Math,this);
};
var arr = [12,56,126,-1,5,15];
console.log(   arr.min()   );

Solution 13 - Javascript

If you are using Underscore or Lodash you can get the minimal value using this kind of simple functional pipeline

_.chain([7, 6, -1, 3, 2]).sortBy().first().value()
// -1

You also have the .min function

_.min([7, 6, -1, 3, 2])
// -1

Solution 14 - Javascript

I think I have an easy-to-understand solution for this, using only the basics of javaScript.

function myFunction() {
            var i = 0;
            var smallestNumber = justPrices[0];
            for(i = 0; i < justPrices.length; i++) {
                if(justPrices[i] < smallestNumber) {
                    smallestNumber = justPrices[i];
                }
            }
            return smallestNumber;
        }

The variable smallestNumber is set to the first element of justPrices, and the for loop loops through the array (I'm just assuming that you know how a for loop works; if not, look it up). If an element of the array is smaller than the current smallestNumber (which at first is the first element), it will replace it's value. When the whole array has gone through the loop, smallestNumber will contain the smallest number in the array.

Solution 15 - Javascript

Here is code that will detect the lowest value in an array of numbers.

//function for finding smallest value in an array
function arrayMin(array){
    var min = array[0];
    for(var i = 0; i < array.length; i++){
    	if(min < array[i]){
    		min = min;
    	}else if (min > array[i]){
    		min = array[i + 1];
    	}else if (min == array[i]){
    		min = min;
    	}
    }
    return min;
};

call it in this way:

var fooArray = [1,10,5,2];
var foo = arrayMin(fooArray);

(Just change the second else if result from: min = min to min = array[i] if you want numbers which reach the smallest value to replace the original number.)

Solution 16 - Javascript

Here is a recursive way on how to do it using ternary operators both for the recursion and decision whether you came across a min number or not.

const findMin = (arr, min, i) => arr.length === i ? min :
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)

Code snippet:

const findMin = (arr, min, i) => arr.length === i ? min :
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)
  
const arr = [5, 34, 2, 1, 6, 7, 9, 3];
const min = findMin(arr, arr[0], 0)
console.log(min);

Solution 17 - Javascript

For anyone out there who needs this I just have a feeling. (Get the smallest number with multi values in the array) Thanks to Akexis answer.

if you have let's say an array of Distance and ID and ETA in minutes So you do push maybe in for loop or something

Distances.push([1.3, 1, 2]); // Array inside an array.

And then when It finishes, do a sort

Distances.sort();

So this will sort upon the first thing which is Distance here. Now we have the closest or the least is the first you can do

Distances[0] // The closest distance or the smallest number of distance. (array).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlisovaccaroView Question on Stackoverflow
Solution 1 - JavascriptzzzzBovView Answer on Stackoverflow
Solution 2 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 3 - Javascripttdowek1View Answer on Stackoverflow
Solution 4 - Javascriptc69View Answer on Stackoverflow
Solution 5 - JavascriptAaron Joel KisonView Answer on Stackoverflow
Solution 6 - JavascriptAlirezaView Answer on Stackoverflow
Solution 7 - JavascriptsurajView Answer on Stackoverflow
Solution 8 - JavascriptAkexisView Answer on Stackoverflow
Solution 9 - JavascriptLibu MathewView Answer on Stackoverflow
Solution 10 - JavascriptTom SöderlundView Answer on Stackoverflow
Solution 11 - JavascriptSabbir AhmedView Answer on Stackoverflow
Solution 12 - JavascriptBugs BunnyView Answer on Stackoverflow
Solution 13 - JavascriptsvarogView Answer on Stackoverflow
Solution 14 - JavascriptSaraView Answer on Stackoverflow
Solution 15 - JavascriptDarrow HartmanView Answer on Stackoverflow
Solution 16 - JavascriptEugen SunicView Answer on Stackoverflow
Solution 17 - JavascriptBKSOView Answer on Stackoverflow