I have an JavaScript array of arrays:
[[-786, 2], [-783, 1], [-782, 5], [-781, 1], [-779, 2], [-778, 1], [-775, 1], [-774, 1], [-773, 1], [-771, 2], [-769, 1], [-767, 1], [-766, 1], [-763, 2], [-760, 2]]
How can I get the biggest element based on value of second element in sub array?
In case above I want to get element:
[-782, 5]
Because 5 is biggest second value in all sub arrays. If there will more than one sub arrays with the bigger second value, I'd like to get first one.
Mariusz
Perform a descending sort based on the second element of each element of the array.
var array = [[-786, 2], [-783, 1], [-782, 5], [-781, 1], [-779, 2], [-778, 1], [-775, 1], [-774, 1], [-773, 1], [-771, 2], [-769, 1], [-767, 1], [-766, 1], [-763, 2], [-760, 2]];
array.sort(function(a, b) {
return b[1] - a[1];
});
console.log(array[0]);
jsFiddle Demo
Please note that while this solution is terse, using sort just for finding the largest or smallest element would be much slower than a for
loop that finds the largest/smallest element in a single iteration.
var array = [[-786, 2], [-783, 1], [-782, 5], [-781, 1], [-779, 2], [-778, 1], [-775, 1], [-774, 1], [-773, 1], [-771, 2], [-769, 1], [-767, 1], [-766, 1], [-763, 2], [-760, 2]];
var maxElementIndex = 0;
for (var i = 0; i < array.length; i++) {
if (array[i][1] > array[maxElementIndex][1]) {
maxElementIndex = i;
}
}
console.log(array[maxElementIndex]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With