Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get biggest array element based on his second sub array value

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

like image 694
sanneo Avatar asked Aug 22 '13 06:08

sanneo


2 Answers

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.

like image 164
c.P.u1 Avatar answered Sep 28 '22 01:09

c.P.u1


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]);
like image 35
vadim Avatar answered Sep 28 '22 03:09

vadim