H.Husain
H.Husain

Reputation: 473

Find first element inside array of arrays with second element having highest value

I have an object like below and I want to output the first string element inside the array of arrays which is having the highest number, which is Australia in this case.

I have tried something like this below but it is not returning the expected, also it will not give the first element inside the array which is a string ["Australia", 127]

The final output must be simple text Australia after checking the data

let data = [
  ["Australia", 23],
  ["Australia", 127],
  ["England", 3],
  ["England", 71],
  ["Australia", 31],
  ["England", 22],
  ["Australia", 81]
];

let maxVals = data.map(function(a) {
  return Math.max.apply(Math, a);
});

console.log(maxVals)

Upvotes: 1

Views: 1049

Answers (3)

Pato94
Pato94

Reputation: 804

Sadly, javascript does not provide a maxBy/minBy in its standard library which is what you're looking for, but this algorithm is very common.

const data = [
  ["Australia", 23],
  ["Australia", 127],
  ["England", 3],
  ["England", 71],
  ["Australia", 31],
  ["England", 22],
  ["Australia", 81]
];
let max = Number.MIN_VALUE;
let maxValue = undefined;
for (let item of data) {
  if (item[1] > max) {
    max = item[1];
    maxValue = item;
  }
}
console.log(maxValue);

Note that this is performance-wise equivalent to the reduce solution, the only difference is that this loop is explicit, and that it'd support empty arrays.

Upvotes: 0

mplungjan
mplungjan

Reputation: 178026

Try sort - it is the simplest for small arrays

NOTE: you can drop the slice if you do not mind to modify the original array

let data = [
  ["Australia", 23],
  ["Australia", 127],
  ["England", 3],
  ["England", 71],
  ["Australia", 31],
  ["England", 22],
  ["Australia", 81]
];


let maxVals = data
  .slice(0)           // only if you do not want to modify the original
  .sort((a,b)=>a[1]-b[1]).pop()[0];

console.log(maxVals)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You could reduce the array and get the array with the first max value. Then get the string.

let data = [["Australia", 23], ["Australia", 127], ["England", 3], ["England", 71], ["Australia", 31], ["England", 22], ["Australia", 81]],
    result = data.reduce((a, b) => a[1] >= b[1] ? a : b)[0];

console.log(result);

Upvotes: 4

Related Questions