0

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.

4
  • 1
    It is a very bad practice to name variables with titlecase in JavaScript; in particular, Array already exists as the array class, and redefining it can have unforeseen consequences. Commented Sep 27, 2016 at 3:42
  • Ah ok, so i'll rename this array. Commented Sep 27, 2016 at 3:45
  • Things is better (as it doesn't overwrite an existing JavaScript built-in), but still bad. Variables, by convention, are in camelcase in JavaScript (words stuck together, first being all lowercase, each consecutive word starting with a capital letter, like so: arrayOfThings). This is a point where all JS style guides agree on; here is Airbnb's. Commented Sep 27, 2016 at 3:52
  • What you are looking for is called "minimum" or "minimum value". Commented Sep 27, 2016 at 5:02

4 Answers 4

1

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,

  • the accumulator starts at +∞
  • when compared to 99, becomes 99
  • when compared to 89, becomes 89
  • when compared to 25, becomes 25

If it were to be compared to a value greater than the current value of the accumulator, it would not change.

Sign up to request clarification or add additional context in comments.

1 Comment

You've essentially rewritten Math.min using reduce.
1

Decompose the problem into two parts you can solve separately (or use existing tools to solve):

  1. Extract the second element of each sub-array--into a new, one-level array.
  2. Find the minimum of an array.

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

Comments

0

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

9 Comments

Normal semantics for taking a minimum are that the "default" value (the result if there are no items) is +Infinity. That also has the advantage of ensuring your code doesn't fail if the array is empty.
@torazaburo Perhaps in JavaScript yes, but it's very common to generally use the first element as the starting max/min. Which is how it's done in the standard algorithms (pseudo) for finding min/max values.
Well, this is JavaScript. Which "standard algorithms" are you referring to? Can you provide a reference? Using the first element doesn't work at all when there is no first element.
@torazaburo There is a first element in this case. More generally there is a check for a empty array before starting. Although it wasn't necessary to include that here.
Well, to beat a dead horse, solutions should do more than just solve the particular example given by the OP. I don't understand why you would choose to add a special check for empty array when the entire problem could be solved by using +Infinity as a default, which is the correct semantics already established by Math.min.
|
-1

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

2 Comments

I'm not sure about the basic strategy of sorting and then taking the first value as a way to find minimum. Although in general performance is not something to worry too much about, this is going to be much slower (probably O(n log n)) than a more straightforward iteration through the object (O(n)) to find the minimum. Among other problems, this requires each string to be parsed as a number up to four times for every single comparison invoked by the sort logic. Then there are edge cases not handled properly such as the array being empty.
You could also optimize your compare function by simply writing return parseInt(a) - parseInt(b).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.