Chaitanya Chauhan Chaitanya Chauhan - 1 month ago 6
Javascript Question

Get 2 Different arrays of top 4 Key and Value as per top values from JSON using javascript

Let's say I have a JSON object.

var JSONObj = "skills":[
{
"skill": "HTML",
"rate": "4"
},
{
"skill": "JS",
"rate": "5"
},
{
"skill": "jQuery",
"rate": "8"
},
{
"skill": "Angular 2",
"rate": "1"
},
{
"skill": "XML",
"rate": "3"
},
{
"skill": "CSS",
"rate": "10"
}
]


I want to generate 2 different arrays for TopRates and TopSkills based on their rate in Javascript.
e.g,
var TopSkills = ["CSS", "jQuery", "JS", "HTML"];
var TopRates = [10, 8, 5, 4]

Answer

You can use reduce() to return arrays of skills and rates and then slice() to return top 4.

var JSONObj = {
  "skills": [{
    "skill": "HTML",
    "rate": "4"
  }, {
    "skill": "JS",
    "rate": "5"
  }, {
    "skill": "jQuery",
    "rate": "8"
  }, {
    "skill": "Angular 2",
    "rate": "1"
  }, {
    "skill": "XML",
    "rate": "3"
  }, {
    "skill": "CSS",
    "rate": "10"
  }]
}

var r = JSONObj.skills.sort((a, b) => b.rate - a.rate).reduce(function(r, e) {
  r.skills = (r.skills || []).concat(e.skill);
  r.rates = (r.rates || []).concat(e.rate);
  return r;
}, {})

var TopSkills = r.skills.slice(0, 4);
var TopRates = r.rates.slice(0, 4);
console.log(TopSkills)
console.log(TopRates)

Comments