0

im taking my first steps with angular and came across this problem. i have this array :

var users = [{
    id: 0,
    'name': 'John',
    'score': '46',
    'difference': 'diff from top'
},{
    id: 0,
    'name': 'Harry',
    'score': '45',
    'difference': 'diff from top'
},{
    id: 0,
    'name': 'Sam',
    'score': '43',
    'difference': 'diff from top'
}];

and i want to get the highest score and store it in a variable (in this case - 46). how can i do that?? im looking for as much "angularish" solution as possible

2
  • Why use angular just to use it? I'd imagine you would want to use vanilla javascript as much as possible before using frameworks to do things, simple things too, such as looping through this array. Also, why does your id not have quotes around it? Commented Jan 9, 2015 at 16:34
  • obviously, my app will do more than just that (hopefully) and the all purpose of this app its to learn angular Commented Jan 9, 2015 at 16:36

2 Answers 2

3

You could try something like this:

Initially, we define a function for finding the max score.

function getHighestScore(array) {
    var max;
    for (var i = 0; i < array.length; i++) {
        if (array[i].score > (max || 0))
            max = array[i].score;
    }
    return max;
}

Then we pass the array of the users to it and get the max score.

var maxScore = getHighestScore(users);
Sign up to request clarification or add additional context in comments.

Comments

0

A one-liner. This won't work in all browsers because of the map function :

Math.max.apply(null, users.map(function(elem) { return +elem.score;}))

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.