How to use loops In Javascript
Example: In this example, we will use JavaScript for loop to get the min and max values from an array of objects
Javascript
// Input array of objects let Arr = [ { "x" : "3/10/2003" , "y" : 0.023452007 }, { "x" : "8/12/2002" , "y" : 0.02504234 }, { "x" : "1/16/2001" , "y" : 0.024533546 }, { "x" : "8/19/2006" , "y" : 0.03123423457 }]; // Initialize min and max values let maxValue = Arr[0].y; let minValue = Arr[0].y; // Getting min and max value using for loops for (let i = 0; i < Arr.length; i++) { if (Arr[i].y > maxValue) { maxValue = Arr[i].y; } if (Arr[i].value < minValue) { minValue = Arr[i].y; } } // Display the output console.log(Arr) console.log( "Max Value:" , maxValue); console.log( "Min Value:" , minValue); |
Output
[ { x: '3/10/2003', y: 0.023452007 }, { x: '8/12/2002', y: 0.02504234 }, { x: '1/16/2001', y: 0.024533546 }, { x: '8/19/2006', y: 0.03123423457 } ] Max Value: 0.03123423457 Min Value: 0.023452...
Max/Min value of an attribute in an array of objects in JavaScript
In this article, we are given an array of objects and the task is to get the maximum and minimum values from the array of objects. For this approach, we have a few methods that will be discussed below.