Reputation: 267
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.
Upvotes: 0
Views: 186
Reputation: 21565
Assuming the second elements are the values we are comparing. We can simply do a standard algorithm to iterate through an array and find the lowest value.
var array = [
["guitar", "99", "guitar.png"],
["vinyl", "89", "vinyl.png"],
["bed", "25", "bed.png"]
];
// Assume the first element has the lowest value
var lowest = +Infinity; // `+` cast to number
array.forEach(function(item) {
if(+item[1] < lowest) lowest = +item[1]; // If we find a lower value update lowest
});
console.log(lowest);
Upvotes: 0
Reputation:
Decompose the problem into two parts you can solve separately (or use existing tools to solve):
For the first, we use map
to create a new array from an old one, by applying some transformation to each element. In this case, the transformation is to extract the second element, and convert it to a number, so:
Things.map(([,num]) => +num))
[,num]
means to assign the second element of the array passed in to the parameter num
), and the the plus sign makes sure it's a number. See below for the non-ES6 version.
For the second, we can just use Math.min
.
Combining these, we can write:
Math.min(...Things.map(([,num]) => +num)))
Math.min(...)
passes all the elements in the mapped array (the numbers) as parameters to Math.min
.
Obligatory disclaimer: the =>
is the ES6 arrow function, the [,num]
is ES6 parameter destructuring (, and ...
is the ES6 parameter spread operator. These will work only in environments that support ES6 one way or another. Otherwise, fall back to
Math.min.apply(0, Things.map(function(elt) { return +elt[1]; }))
Upvotes: 1
Reputation: 198304
var array = [
["guitar", "99", "guitar.png"],
["vinyl", "89", "vinyl.png"],
["bed", "25", "bed.png"]
];
min_second = array.reduce(function(a, x) {
var b = parseFloat(x[1]);
return a < b ? a : b;
}, Number.POSITIVE_INFINITY);
console.log(min_second);
array.reduce
will apply the callback function to the accumulator and each consecutive element, and assign the result to the accumulator; the accumulator starts at +∞. The intent of the callback is that each element whose second value (converted to a number) is less than that becomes the new accumulator. Thus,
If it were to be compared to a value greater than the current value of the accumulator, it would not change.
Upvotes: 1
Reputation: 1190
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]);
Upvotes: -1