Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain smallest value from array in Javascript?

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?

like image 650
lisovaccaro Avatar asked Jan 19 '12 23:01

lisovaccaro


1 Answers

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)
like image 63
zzzzBov Avatar answered Oct 20 '22 16:10

zzzzBov