Discovering the minimum and maximum within an array containing objects

I am working with an array of objects that contain latitude and longitude points:

var pts = [
    { "X": 52.67528921580262,  "Y": 8.373513221740723 },
    { "X": 52.6759657545252,   "Y": 8.374114036560059 },
    { "X": 52.682574466310314, "Y": 8.37256908416748  },
    { "X": 52.68356308524067,  "Y": 8.373942375183105 },
    { "X": 52.68293869694087,  "Y": 8.375487327575684 },
    { "X": 52.67685044320001,  "Y": 8.376259803771973 },
    { "X": 52.6756535071859,   "Y": 8.379607200622559 },
    { "X": 52.676017795531436, "Y": 8.382096290588379 },
    { "X": 52.68101344348877,  "Y": 8.380722999572754 },
    { "X": 52.68351105322329,  "Y": 8.383641242980957 },
    { "X": 52.68,              "Y": 8.389             }
];

Could someone help me determine the minimum and maximum values for X and Y in this array?

Answer №1

To achieve the desired result, you can utilize the `Math.min` and `Math.max` functions by passing in a mapped array that includes only the specified values as shown below:

function calculateBoundaryValue(mathFunction, dataValues, propertyKey) {
    return Math[mathFunction].apply(dataValues, dataValues.map(function (entry) {
        return entry[propertyKey];
    }));
}

var highestYValue = calculateBoundaryValue("max", coordinates, "Y"), // 8.389
    lowestYValue = calculateBoundaryValue("min", coordinates, "Y"); // 8.37256908416748

Answer №2

To simplify things, it may be best to organize the array in ascending order based on the x values.

array.sort(function minXToMaxX(a,b){
   return a.x - b.x;
});

The smallest x value can be found at index array[0]. The largest x value is located at index array[array.length - 1];

Answer №3

This particular code is functioning perfectly. Take a look at the snippet for a demonstration.

var pts = [{
  "X": 52.67528921580262,
  "Y": 8.373513221740723
}, {
  "X": 52.6759657545252,
  "Y": 8.374114036560059
}, {
  "X": 52.682574466310314,
  "Y": 8.37256908416748
}, {
  "X": 52.68356308524067,
  "Y": 8.373942375183105
}, {
  "X": 52.68293869694087,
  "Y": 8.375487327575684
}, {
  "X": 52.67685044320001,
  "Y": 8.376259803771973
}, {
  "X": 52.6756535071859,
  "Y": 8.379607200622559
}, {
  "X": 52.676017795531436,
  "Y": 8.382096290588379
}, {
  "X": 52.68101344348877,
  "Y": 8.380722999572754
}, {
  "X": 52.68351105322329,
  "Y": 8.383641242980957
}, {
  "X": 52.68,
  "Y": 8.389
}];
var xobj = [];
var yobj = [];
var len = pts.length;

for (var i = 0; i < len; i++) {

  xobj.push(parseFloat(pts[i].X));
  yobj.push(parseFloat(pts[i].Y));
}

//highest x value
var value = xobj[0];
for (var n = 1; n < xobj.length; n++) {
  if (xobj[n] > value) {
    value = xobj[n];
  }
}

//lowest x value
var valuel = xobj[0];
for (var n = 1; n < xobj.length; n++) {
  if (xobj[n] < valuel) {
    valuel = xobj[n];
  }
}

//highest y value
var valueY = yobj[0];
for (var n = 1; n < yobj.length; n++) {
  if (yobj[n] > valueY) {
    valueY = yobj[n];
  }
}

//lowest y value
var valuelY = yobj[0];
for (var n = 1; n < yobj.length; n++) {
  if (yobj[n] < valuelY) {
    valuelY = yobj[n];
  }
}

document.getElementById("demo").innerHTML = valuel

document.getElementById("demo1").innerHTML = value

document.getElementById("demo2").innerHTML = valuelY

document.getElementById("demo3").innerHTML = valueY
MinX:
<p id="demo"></p>
MaxX:
<p id="demo1"></p>
MinY:
<p id="demo2"></p>
MaxY:
<p id="demo3"></p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

unnecessary files in the node_modules directory in Rails

I am a beginner in Node.js and unfamiliar with npm and modular JavaScript. After using the browserify-rails gem, I noticed that there are multiple files from a GitHub repo stored in the node_modules folder after running npm install. Since I only require ...

Retrieve information for AJAX tooltip from a specific URL

I am currently utilizing a script for tooltips. Is there a method available to dynamically load the content of a tooltip from a URL (using dynamic content loaded from a PHP script) rather than specifying the path to an html/php file? For Example What I ...

What methods can I utilize to prevent pop-up errors from appearing in my javascript code?

Recently, I've been working on utilizing an innovative IBM tool called Presto that efficiently transforms traditional green screens into browser-based pages. While the process is effective, it involves some quirky behaviors. One particular challenge I ...

Displaying Material UI Styles: A Challenge

Currently working on a website using Material-UI and React. Strangely, the styling applied through Material-UI's Hook API functions perfectly on codesandbox.io but fails to work when running locally. Notably, the border radius feature fails to update ...

The animation in an AngularJS directive only functions properly when utilizing $timeout

I can't seem to figure out why the animation is not working as intended in the code below: app.directive('openMenu', ['$animate', '$timeout', function($animate, $timeout) { return { link: function(scope, elem ...

a guide to structuring REST API requests with axios in Vue.js

In my Vue.js app, I am utilizing Axios to consume a REST API. Each time I make an API call, I create a new instance of Axios with the necessary authentication headers by calling axios.get in various places. // UserdataComponent.vue const anInstance = axio ...

I'm looking to create a unit test for my AngularJS application

I am currently working on a weather application that utilizes the to retrieve weather data. The JavaScript code I have written for this app is shown below: angular.module('ourAppApp') .controller('MainCtrl', function($scope,apiFac) { ...

Sending an array via Ajax using jQuery

I'm trying to send 4 data elements via ajax post - 3 text strings and a multidimensional array of text strings. However, when I send the ajax request, only the 3 text strings are received, not the array. Here's my function that includes the ajax ...

Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API. // Raise isLoading flag this.$store.commit('isLoading', true); // Initial data fetch this.$s ...

What is the best method for retrieving all input fields within a form that are of the types text, password, file, textarea, and selectbox?

Is there a way to retrieve all input fields of specific types within a form using jQuery? jQuery("#signup-form").find('input').each(function(index, element) { }); I am aware that I can target text boxes with: jQuery("#signup-form").find(&apos ...

The server encountered a 500 Internal Server Error because it could not read the 'username' property of an undefined object

When attempting to register a user in a mongodb database using express, a POST call was made to localhost:3000/users/register The request body included: { "firstName": "Jason", "lastName": "Watmore", "username": "jason", "email": "<a ...

Encountering issues with Jquery while retrieving data from a .json URL

While attempting to retrieve data using a small script that usually works with URLs producing JSON data, I encountered a syntax error when trying it with a URL ending in .json. //error Uncaught SyntaxError: Unexpected token : http://frontier.ffxiv.com/wo ...

Guide to embedding a qr code within a pdf document

I've been working on creating a PDF file generation feature where users can download the PDF with a QR code embedded in it. While I've successfully implemented the PDF generation part, I'm facing an issue with adding the QR code to the file. ...

Issue with event binding on datepicker that is dynamically added is not functional

I have integrated the Kendo datepicker into my project, and I am facing an issue with duplicated div elements containing datepickers. The problem is that the datepicker events only fire once on the first duplicated div and then stop working altogether. I ...

A script in PHP or JavaScript that dynamically generates two dual drop-down menus to assist with data selection

I have experience with php scripting, but I am facing challenges when trying to combine it with JavaScript. The issue arises when I have a form that includes dropdown menus for categories and subcategories. When a category is selected, the options in the s ...

Accessing specific elements within multi-dimensional arrays using JavaScript

I've embarked on the exciting journey of creating my own 'Choose Your Adventure!' game, but I've hit a snag. I'm struggling to effectively target specific values within the multi-dimensional array I constructed. In order to add som ...

Using PHP, JavaScript is unable to hide <div> elements

I'm encountering an issue where the div I want to show when an error occurs is not hiding and showing properly using JavaScript. Here is a snippet of my code: <script> function hideerror() { var catdiv = document.getElementById(error); ...

Django RGBField cannot locate jQuery

Working on a project that utilizes an RGBField, the following script is injected into the template (nested deep within django's structure, as its exact location remains elusive): <script type="text/javascript"> (function($){ ...

Error message: Unforeseen node express token problem

Whenever I attempt to call the endpoint provided below, Postman returns an error as shown: { "success": false, "error": "Unexpected token / in JSON at position 7" } Within the addFollowing function, you'll notice that I ...

The list filter may not work properly if the search string is left blank

I am currently working on a list filtering feature that updates based on user input. As the user types, the system compares the entered text against the items in the list and displays the matching objects in an array. However, I'm facing an issue - wh ...