-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"
}
2

4 Answers 4

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

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

1 Comment

@Developer mark this answer as the accepted answer if this worked for you in order to mark your question as solved
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);

Comments

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

1 Comment

This won't work for { "sport" : "Tennis", "score" : "-12000" }
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.