3

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?

3 Answers 3

3

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.

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

Comments

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

Comments

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

console.log(result);

Comments

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.