1

I am using this tutorial to get the largest 'first' [0] value of a multidimensional array.

array = [[1, 5], [4, 7], [3, 8], [2, 3],  
 [12, 4], [6, 6], [4, 1], [3, 2], 
 [8, 14]]

 array.reduce(function(max, arr) {
        return max >= arr[0] ? max : arr[0];
}, -Infinity);

but how can i get other associated values? In other words since [12, 4] 12 is the highest value but how can i get '4'?
*note after sorting the arrays from the first val, i would need access to all the values.

Community
  • 1
  • 1
t q
  • 4,593
  • 8
  • 56
  • 91

3 Answers3

2

That code only check the first value of the nested array. If it's fine to you, you have just to store the whole nested array, instead the first value. So:

var result = array.reduce(function(max, arr) {
    return max[0] >= arr[0] ? max : arr;
});

Notice that I removed -Infinity, in that case the first iteration would start already with the first item of the array ([1, 5] in your case). So now you can access to 12 using result[0] and 4 using result[1].

ZER0
  • 24,846
  • 5
  • 51
  • 54
  • thank you, i updated my question. i would need access to all the values after the sort – t q Feb 20 '15 at 20:05
  • It's not clear what you want. Do you want to obtain `[12, 4]` as result – where the first item is the largest first item in the "parent"'s array – or do you want to sort all the values using the first item as index? To be clear, in the second case you just sort the original array, so you would obtain another multi-dimensional array as result. – ZER0 Feb 20 '15 at 20:12
  • your fist comment is what i am after. after the sort, i will need `[12,4]` (all values). i think your post is what i am after, will check as soon as i can. – t q Feb 20 '15 at 20:15
  • In that case my answer was doing exactly what you need. You will get `[12, 4]` in `result` variable – providing the `array` from your original question. – ZER0 Feb 20 '15 at 20:17
1

It sounds like you want to sort the list and grab the second item from the first result:

array.sort(function(a,b) { 
   return a[0] > b[0] ? -1 : 1 
})[0][1]; -- 4
Malk
  • 11,855
  • 4
  • 33
  • 32
  • thank you, i would need both values. and in the case of multiple values i would need them all after sorting the first value of the set – t q Feb 20 '15 at 20:02
  • I'm glad this helps, but ZERO's answer might be more appropriate for this particular use case since reduce only enumerates the list once while sort can parse it several times. Also, the end `result` would contain all additional values just as this would. – Malk Feb 20 '15 at 20:54
0

You can try the following:

array.reduce(function(max, arr) {
    return max >= arr[0] ? max : arr[0];
});

Or you can use Math.max:

array.reduce(function(max, arr) { 
    return Math.max(max, arr[0]); 
});
m0bi5
  • 8,900
  • 7
  • 33
  • 44