billy_comic
billy_comic

Reputation: 899

compare multidimensional array to find array with largest value javascript

I have a multidimensional array that has name and integer values in them. I need to be able to compare the integer value in each array in the multidimensional array. how can I compare and return that array?

var totals = [
    ['john', 'test', 45],
    ['bob', 'tester', 75]
];

How can I loop over the arrays in the "totals" array and return the one with the largest integer value?

Upvotes: 3

Views: 112

Answers (3)

Koushik Das
Koushik Das

Reputation: 10793

var result = totals.reduce((p, c) => {
    return p[2] > c[2] ? p : c;
});

console.log(result);

Upvotes: 0

Moshe Karmel
Moshe Karmel

Reputation: 459

var largest = totals.reduce((prev, cur) => prev[2] > cur[2] ? prev : cur, [0,0,0]);

Upvotes: 0

Matt Way
Matt Way

Reputation: 33141

You could use reduce. For example:

var totals = [
    ['john', 'test', 45],
    ['john', 'test', 46],
    ['john', 'test', 42],
    ['john', 'test', 41]
];

var biggest = totals.reduce((a, b) => a[2] > b[2] ? a : b);
console.log(biggest);

Fiddle here


It should be noted, that if reduce() is not supplied with an initial value, then a becomes the first, and b becomes the second in the first call.

Upvotes: 3

Related Questions