1

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)

0

3 Answers 3

4

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);

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

2 Comments

it takes a single loop. your one uses sorting, which is in the best case O(nlogn).
0

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)

Comments

0

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.

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.