-3

In an array like below:

[{
    "sport" : "Cricket",
    "score" : "22.45"
},
{
    "sport" : "Tennis",
    "score" : "-12"
}]

I would like to iterate the JSON and find the array with lowest value of score. In this case get

{
    "sport" : "Tennis",
    "score" : "-12"
}
ellipsis
  • 12,049
  • 2
  • 17
  • 33
Developer
  • 45
  • 6
  • Possible duplicate of [Javascript get object from array having min value and min value is needs to find and then find object](https://stackoverflow.com/questions/43062868/javascript-get-object-from-array-having-min-value-and-min-value-is-needs-to-find) and [Finding object with lowest value for some key, in Javascript](https://stackoverflow.com/questions/26652327) – adiga Mar 11 '19 at 09:50
  • [How much effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Mar 11 '19 at 09:54

4 Answers4

1

Sort in ascending order based on the score and return the first object

var a = [{
    "sport": "Cricket",
    "score": "22.45"
  },
  {
    "sport": "Tennis",
    "score": "-12"
  }
];
console.log(a.sort((a, b) => a.score - b.score)[0])
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

Try this to Get array from JSON Array with lowest key's value

let myArray =[{
    "sport" : "Cricket",
    "score" : "22.45"
},
{
    "sport" : "Tennis",
    "score" : "-12"
},
{ "sport" : "Tennis", "score" : "-12000" }]

let minOfArray =myArray.reduce(function(prev, curr) {
    return parseInt(prev.score) < parseInt(curr.score) ? prev : curr;
});

console.log(minOfArray);
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
0

You should use parseInt:

var arr = [{
    "sport" : "Cricket",
    "score" : "22.45"
},
{
    "sport" : "Tennis",
    "score" : "-12"
},
{
    "sport" : "Tennis",
    "score" : "-12000"
}];

var res = arr.reduce((a,c) => parseInt(c.score) < parseInt(a.score) ? c : a);
ttulka
  • 10,309
  • 7
  • 41
  • 52
0

You can use reduce to iterate on your items and get the lowest score:

const data = [{
  "sport" : "Cricket",
  "score" : "22.45"
}, {
  "sport" : "Tennis",
  "score" : "-12"
}];

const result = data.reduce((acc, x) => x.score < acc.score ? x : acc, data[0]);

console.log(result);
jo_va
  • 13,504
  • 3
  • 23
  • 47