1

Couldn't find anything about this.

I have this controller:

app.controller('StatsCtrl', function ($scope, $http) {
 $http.get('stats.json').success(function(data) {
    $scope.stats = data;
 });
});

The stats.json has:

{"lang":{"en":28,"und":1,"ja":9,"es":14,"ru":1,"in":1,"ko":1,"th":1,"ar":1}}

What I need is to assign the maximum value from the lang object to $scope.max in the controller. What is the best way to do this?

2
  • Do you want to assign value(number) to max or key(like "en", "und") to max ? Commented Nov 6, 2015 at 11:03
  • @user2393267 the value(number) which would be 28 in this case. Commented Nov 6, 2015 at 11:06

3 Answers 3

2

https://jsfiddle.net/kaiser07/6h317Lvv/

  var jsonText = '{"lang":{"en":28,"und":1,"ja":9,"es":14,"ru":1,"in":1,"ko":1,"th":1,"ar":1}}';
    var data = JSON.parse(jsonText).lang
    var maxProp = null
    var maxValue = -1
    for (var prop in data) {
      if (data.hasOwnProperty(prop)) {
        var value = data[prop]
        if (value > maxValue) {
          maxProp = prop
          maxValue = value
        }
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it with a couple of native methods:

$scope.max = Math.max.apply(null, Object.keys(data.lang).map(function(key) {
    return data.lang[key];
}));

2 Comments

Added this to the controller, but I think I'm missing something, because it doesn't work: app.controller('StatsCtrl', function ($scope, $http) { $http.get('stats.json').success(function(data) { $scope.stats = data; }); $scope.max = Math.max.apply(null, Object.keys(data.lang).map(function(key) { return data.lang[key]; })); });
Oops, it's working now. Thanks. app.controller('StatsCtrl', function ($scope, $http) { $http.get('stats.json').success(function(data) { $scope.stats = data; $scope.max = Math.max.apply(null, Object.keys(data.lang).map(function(key) { return data.lang[key]; })); }); });
1

I would suggest to use underscore.js _.max:

_.max(list, [iteratee], [context])

Returns the maximum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. -Infinity is returned if list is empty, so an isEmpty guard may be required.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.max(stooges, function(stooge){ return stooge.age; });
=> {name: 'curly', age: 60};

link

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.