How to get min and max value from json in angular js

I want to get the maximum and minimum value from json in angular js my json:

{ "data":[ { "name": "ranjith", "age": 22 }, { "name": "rahul", "age": 20 }, { "name": "jinesh", "age": 25 }, { "name": "vishnu", "age": 24 } ] } 

and my controller: -

 var app = angular.module('myApp', ['']); app.controller('myCtrl', function($scope, data) { $scope.data = data.data; $scope.min=""; $scope.max=""; }; }); 

I want to get the minimum and maximum value from an array and store it in the variables min and max

+5
source share
5 answers

You can just use

 $scope.min = Math.min.apply(Math,$scope.data.map(function(item){return item.age;})); $scope.max = Math.max.apply(Math,$scope.data.map(function(item){return item.age;})); 
+13
source

To avoid using third-party lib

  for (var index in $scope.data.data) { var item=$scope.data.data[index]; if($scope.min==0 && $scope.max==0){ // set first default element $scope.min=item.age; $scope.max=item.age; } else{ if($scope.min>item.age) $scope.min=item.age; else if($scope.max<item.age) $scope.max=item.age; } } 
+2
source

You can use Underscore.js with angular, and then in your controller,

 var ageArr = _.pluck(data.data, 'age'); $scope.min= _.min(ageArr); $scope.max= _.max(ageArr); 

Plunker url http://run.plnkr.co/plunks/Mw531cqUIHVSorb5kOac/

+1
source

1.Add underline dependency

2. Use the following:

 //For Maximum Age: _.max(data, function(itr){ return itr.age; }); /* O/p = { "name": "jinesh", "age": 25 }*/ //For Minimum Age: _.min(data, function(itr){ return itr.age; }); /* O/p = { "name": "rahul", "age": 20 } */ 
0
source

If the intention will be displayed, you can immediately proceed to min: {{(data | orderBy:'age')[0].age}}

0
source

Source: https://habr.com/ru/post/1241707/


All Articles