0

I'm looking to return the skill below from a variable:

const skillsData = [
  { name: "React", value: 390 },
  { name: "CSS", value: 1200 },
  { name: "JavsScript", value: 540 },
  { name: "HTML", value: 1900 },
  { name: "CSS", value: 1278 },
];

Within a function, I am using the following:

let maxSkills = Math.max.apply(Math, skillsData.map(function(o) { return o.value; }))

This will obviously return a value, which has worked for one case, however what is the correct way to return the following 'name' key on the basis?

Furthermore, what would be a function to sort these in ascending value, so that you return HTML as the last in JSON?

n_d22
  • 413
  • 4
  • 12
  • what are you trying to do? are you trying to get the name property of the object with the highest value property or sort them by value property? – about14sheep Jan 02 '22 at 02:17
  • Hi about14sheep, I'm actually trying to do both. I would like to sort them by value property in the json, but I would also like to return the highest 'name' key on the basis of the value and store it in a variable as above. – n_d22 Jan 02 '22 at 02:20
  • If you sort it in either direction, `HTML` would be neither last nor first. – konsolebox Jan 02 '22 at 02:21
  • you can use [this SO question](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) to figure out how to sort the array based on a property. Then just have a variable set to the first index of that array to isolate the maximum – about14sheep Jan 02 '22 at 02:27

2 Answers2

1

Sort the array by using the sort method.

This will produce the array sorted in descending order:

skillsData.sort((a, b) => b.value - a.value)

and ascending order:

skillsData.sort((a, b) => a.value - b.value)

The following code will print the .name value of the first element in the sorted array. The first element holds the maximum value, as sortedSkillsData is in descending order.

const skillsData = [
  { name: "React", value: 390 },
  { name: "CSS", value: 1200 },
  { name: "JavsScript", value: 540 },
  { name: "HTML", value: 1900 },
  { name: "CSS", value: 1278 },
];

let sortedSkillsData = skillsData.sort((a, b) => b.value - a.value);
let maxSkills = sortedSkillsData[0].name;
console.log(maxSkills);
Vektor
  • 697
  • 5
  • 14
-1

You can use sort method and sort in ascending order and then get the last element and then property name from that.

const skillsData = [
  { name: "React", value: 390 },
  { name: "CSS", value: 1200 },
  { name: "JavsScript", value: 540 },
  { name: "HTML", value: 1900 },
  { name: "CSS", value: 1278 },
];

const maxSkills = skillsData.sort((a, b) => a.value - b.value).slice(-1)[0].name
console.log(maxSkills)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176