Determining the Minimum and Maximum Values within a JSON Array of Dictionaries

I'm struggling to extract the highest and lowest values from my dataset. While resources like Get the largest value from Json object with Javascript and Math.min.apply returns 0 for null seem promising, my data is more complex than I anticipated.

My dataset consists of life expectancy data for all countries from 1995 to 2016:

[{"country":"Abkhazia","1995":null,"1996":null,"1997":null,"1998":null,"1999":null,"2000":null,"2001":null,"2002":null,"2003":null,"2004":null,"2005":null,"2006":null,"2007":null,"2008":null,"2009":null,"2010":null},
{"country":"Afghanistan","1995":null,"1996":null,"1997":null,"1998":null,"1999":null,"2000":null,"2001":null,"2002":5.7,"2003":6.8,"2004":6.4,"2005":6.6,"2006":6.8,"2007":7.3,"2008":7.0,"2009":7.6,"2010":7.6},
{"country":"Akrotiri and Dhekelia","1995":null,"1996":null,"1997":null,"1998":null,"1999":null,"2000":null,"2001":null,"2002":null,"2003":null,"2004":null,"2005":null,"2006":null,"2007":null,"2008":null,"2009":null,"2010":null},
{"country":"Albania","1995":2.6,"1996":4.0,"1997":4.8,"1998":5.3,"1999":5.8,"2000":6.4,"2001":6.0,"2002":6.3,"2003":6.2,"2004":6.9,"2005":6.8,"2006":6.7,"2007":6.9,"2008":6.7,"2009":6.9,"2010":6.5},
etc.

Requested Information:

I need to identify the highest and lowest values in the entire dataset.
In this sample, it would be:

min: 2.6
max: 7.6

I am working on a datamap using D3 and intend to use these values to establish a color range.

Attempted Code:

Although I believe a combination of the provided links could solve my issue, I have been struggling to implement it. For instance, while the second link allows me to find the minimum value for a specific country, I cannot determine the overall minimum across all countries.

Hoping for assistance!

Answer №1

One way to find the min and max values in a dataset is to iterate over all countries and keys, checking for non-null values. Once found, you can determine the minimum and maximum values.

var data = [{ "country": "Abkhazia", "1995": null, "1996": null, "1997": null, "1998": null, "1999": null, "2000": null, "2001": null, "2002": null, "2003": null, "2004": null, "2005": null, "2006": null, "2007": null, "2008": null, "2009": null, "2010": null }, { "country": "Afghanistan", "1995": null, "1996": null, "1997": null, "1998": null, "1999": null, "2000": null, "2001": null, "2002": 5.7, "2003": 6.8, "2004": 6.4, "2005": 6.6, "2006": 6.8, "2007": 7.3, "2008": 7.0, "2009": 7.6, "2010": 7.6 }, { "country": "Akrotiri and Dhekelia", "1995": null, "1996": null, "1997": null, "1998": null, "1999": null, "2000": null, "2001": null, "2002": null, "2003": null, "2004": null, "2005": null, "2006": null, "2007": null, "2008": null, "2009": null, "2010": null }, { "country": "Albania", "1995": 2.6, "1996": 4.0, "1997": 4.8, "1998": 5.3, "1999": 5.8, "2000": 6.4, "2001": 6.0, "2002": 6.3, "2003": 6.2, "2004": 6.9, "2005": 6.8, "2006": 6.7, "2007": 6.9, "2008": 6.7, "2009": 6.9, "2010": 6.5 }],
    min = Number.MAX_VALUE,
    max = -Number.MAX_VALUE;

data.forEach(function (o) {
    Object.keys(o).forEach(function (k) {                
        if (k !== 'country' && o[k] !== null) {
            min = Math.min(min, o[k]);
            max = Math.max(max, o[k]);
        }
    });
});

console.log(min, max);

Answer №2

For those with permission to utilize ES6:

const highestValue = data.reduce( (max, item)  => {
    let arr = [max];
    for(const property in item) {
        if (isNaN(Number.parseFloat(item[property]))) continue;
        arr.push(item[property]):
    }
    return Math.max.apply(arr, Math);
}, -1)

Answer №3

If you're looking to validate all elements in an array as numbers and find the min/max values, check out this code snippet below. Simply hit run to see the outcome.

data = [{"country":"Abkhazia","1995":null,"1996":null,"1997":null,"1998":null,"1999":null,"2000":null,"2001":null,"2002":null,"2003":null,"2004":null,"2005":null,"2006":null,"2007":null,"2008":null,"2009":null,"2010":null},
{"country":"Afghanistan","1995":null,"1996":null,"1997":null,"1998":null,"1999":null,"2000":null,"2001":null,"2002":5.7,"2003":6.8,"2004":6.4,"2005":6.6,"2006":6.8,"2007":7.3,"2008":7.0,"2009":7.6,"2010":7.6},
{"country":"Akrotiri and Dhekelia","1995":null,"1996":null,"1997":null,"1998":null,"1999":null,"2000":null,"2001":null,"2002":null,"2003":null,"2004":null,"2005":null,"2006":null,"2007":null,"2008":null,"2009":null,"2010":null},
{"country":"Albania","1995":2.6,"1996":4.0,"1997":4.8,"1998":5.3,"1999":5.8,"2000":6.4,"2001":6.0,"2002":6.3,"2003":6.2,"2004":6.9,"2005":6.8,"2006":6.7,"2007":6.9,"2008":6.7,"2009":6.9,"2010":6.5}];

values = [];

for (i in data) {
  for (j in data[i]) {
    if (parseFloat(data[i][j]) > 0) {
      values.push(parseFloat(data[i][j]));
    }
  }
}

min = Math.min.apply(null, values);
max = Math.max.apply(null, values);
alert(values)
alert(min);
alert(max);

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

The Angular framework is unable to locate a differ that supports the object '[object Object]' which is of type 'object'

In my Angular project, I am calling an API and receiving the following JSON data: { "id": 16, "poste": "ameur taboui", "desciption": "f", "service": "f", ...

Using the ng-repeat directive to create dynamic data-titles in AngularJS

I need help with displaying dynamic headers in an Angular table for certain <td> elements. Here is a sample of my data: let data = [ { id: 1, name: 'name', fields: { field1: { value: '123&apo ...

Preserving Selected Dropdown Options After Form Submission

My PHP form consists of 7 fields, with 6 of them being required. One of the mandatory fields is an age dropdown that I'm filling in using JavaScript. The issue I'm encountering is that when a user enters information for 5 out of the 6 required f ...

VueJs: Finding the corresponding value of a data object

Is there a way to extract data from an object in Vue? This is the format of my data: datasets: [{ text:"Cars", value: "[1,2,3]" }, { text:"Trains", value: "[1,4,10] } ] When I receive information from route props like this: this.selectedText= this ...

The validation of forms using ajax and jsp is not functioning

I've been working on developing a username validation system using JSP and AJAX, but I keep encountering an error that looks like this: POST ://localhost:8080/web_application/deneme.jsp Error Message: 405 (Method Not Allowed) This is my JSP page, c ...

What is the process for uploading a JSON file from your local drive?

I am attempting to use jQuery to load a local JSON file. The code seems to be functioning properly, but for some reason, the data is not being made available in an array. $.getJSON("/ajax/data/myjasonfile.json", function(json) { console.log(js ...

Converting JSONObject into a Document

Hello, I am new to using MongoDB and I am trying to figure out how to convert a JSONObject to a Document and then store it in MongoDB. Here is the code snippet that I have so far - I receive a service API response in JSON format. CloseableHttpResponse res ...

Is there a way to assign a value to the property in AngularJS' ng-options?

There seems to be a common issue that many people (myself included) are facing. When utilizing the ng-options directive within AngularJS to populate the choices for a <select> element, I am struggling to understand how to assign a value to each opti ...

Troubleshooting React and Material-UI: Adjusting <slider> component for use with personalized data

I am facing a challenge with using the Material-UI slider to showcase API data. The unique aspect here is that the slider is intended for displaying data without any interactivity. Encountering an error message: Slider.js:91 Uncaught TypeError: nearest.to ...

Optimal methods for handling Ajax requests in the present day

Recently, I revisited some websites I co-built with a friend and was working on getting them functional again. It's been a while since I've done any AJAX work, and I'm realizing that there aren't many resources available to help trouble ...

Easily accessible jQuery tabs with the option to directly link to a specific tab

I currently have tabs set up on my webpage. The code for these tabs is as follows: $('ul#tabs li a').click(function(){ var id = $(this).attr('id'); var counter = 1; $("ul#tabs a.current").removeClass('cur ...

Discovering the technique to interact with obscured objects through a haze of PointsMaterial in three.js

Is there a property that allows objects behind a fog of multiple points to be clickable? I want to be able to click on objects even when they are obscured by the fog. Below is the code I am using to create and animate the fog: const loadFogEffect = () =&g ...

Does the JSON file adhere to the correct formatting guidelines?

While exploring, I came across a .json file organized in the following manner: "property1":"graph_example" "property2":false "property3":true "property4":null { "objectType": "some_type", "name": "name_1", "operation": "operation_1", "numericValue": 3} ...

What is the process of setting up an array and populating it with characters from a buffer

In my code, there is a method that looks like this: int create_nodes(Source* source, int maxTokens) { int nodeCount = 0; Token* p_Tstart = source->tknBuffer; Token* p_Tcurrent = source->tknBuffer; while ((p_Tcurrent - p_Tstart) < ...

What is the JSON Schema counterpart to XSD's maxOccurs property?

I've been scouring the internet for hours, but I can't seem to find any examples that match my specific query. I have a condensed XSD schema like this: <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name= ...

I am finding that the text I am creating using context.fillText keeps getting distorted within the canvas

I am attempting to place text inside a canvas element. The HTML markup for the canvas is as follows: <canvas id="leaderboard2" style="position: fixed; right: 1250px; top: 140px; width: 230px; height: 330px;"></canvas>. Des ...

Using Dotnetnuke WebService in conjunction with jQuery for making POST requests

I am currently working on a dotnetnuke module and encountering multiple challenges when trying to connect to a webservice using JavaScript to fetch data. Here is the JavaScript code I am using: function Test() { $.ajax({ type: "POST", ...

How can I change a textarea to uppercase?

I'm looking to create a textarea that automatically types in all capital letters, regardless of the user's input or whether they are holding down the shift key. I want it to accept any input and convert it to uppercase on the fly without showing ...

Encountering the error "Cannot read property 'header' of undefined" while conducting tests on Nodejs using supertest

In my server.js file, I have set up my express app. I tried to run a demo test in my test file using express, but unfortunately, the test did not run successfully. const request = require('supertest'); const express = require('express' ...

JSON and autocomplete feature causing performance problems

Developing an application that functions both online and offline using technologies like application cache and local storage is my current project. Utilizing jQuery mobile along with a jqm autocomplete solution from , I aim to create a seamless user experi ...