beriliox beriliox - 2 months ago 7
Javascript Question

How to get the minimum value from a multi-dimensional array?

I'm trying to get the lower numeric value from a multi-dimensional array. Just like this.

var Things = [
["guitar", "99", "guitar.png"],
["vinyl", "89", "vinyl.png"],
["bed", "25", "bed.png"]
];


I would like to return an alert of the lower value, like this:

alert() // 25


If anybody could help me, would be very grateful.

Answer

Try it using sort function:

function compare(a,b) {
  if (parseInt(a[1]) < parseInt(b[1]))
    return -1;
  if (parseInt(a[1]) > parseInt(b[1]))
    return 1;
  return 0;
}

var myArray = [
        ["guitar", "99", "guitar.png"],
        ["vinyl", "89", "vinyl.png"],
        ["bed", "25", "bed.png"]
    ];

myArray.sort(compare);

alert(myArray[0][1]);