Locate the highest and lowest values within a .json file

When working on a graph using d3.js, one key step is setting up the scales for the axis.

The data for the graph is stored in a Json file with multiple arrays, each representing different regions and years:

[{
    "id" : "AustraliaNewZealand" ,
    "year" : [1990,1992,1994,1993,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010],
    "value":[477790,485825,487296,488885,502585,511718,526594,538967,550556,563572,577171,579126,591635,599216,604267,608954,615853,623685,618961,614920]
}, 
{
    "id":"CentralEurope",
    "year":[1990,1992,1994,1993,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010],
    "value":[1548736,1334452,1313088,1283248,1314709,1360546,1343907,1285511,1237278,1251872,1244069,1233778,1284639,1297510,1317861,1359787,1396681,1361445,1278731,1343044]
}, 
{
    "id":"EasternEurope",
    "year":[1990,1992,1994,1993,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010],
    "value":[4418516,3530464,3287987,2925644,2775181,2672238,2540975,2495036,2513372,2515375,2540796,2544848,2598148,2637682,2622241,2709974,2714204,2740248,2565213,2680226]
}, 
{
    "id":"NorthAmerica",
    "year":[1990,1992,1994,1993,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010],
    "value":[6750754,6821412,6948829,7059001,7166869,7386971,7460485,7509719,7573562,7790060,7675762,7710685,7769154,7896824,7918461,7841686,7966277,7751508,7277713,7493948]
}, 
{
    "id":"WesternEurope",
    "year":[1990,1992,1994,1993,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010],
    "value":[4365949,4290345,4222425,4221029,4264725,4353056,4290057,4310736,4251628,4260565,4306230,4278128,4333237,4337031,4305560,4267515,4209481,4125479,3841580,3924831]
}]

Ideally, I want to iterate through all the arrays to find the minimum and maximum values for years and values across all regions. One way to achieve this is by using a for loop, but figuring out where and how to implement it remains a challenge.

var xScale = d3 .time.scale()
                .domain((d3.extent(dataset[0].year)))
                .range([margin*2, (width - margin)]);
var yScale = d3 .scale.linear()
                .domain([0, d3.max(dataset[0].value)])
                .range([(height - margin), margin]);

Answer №1

Experience the joy of incorporating a touch of functional programming in place of utilizing for loops:

d3.extent(dataSet.reduce(function(x,y) { return x.concat(y.month) }, []))

You have the capability to apply this method to the data values as well.

Answer №2

The Math functions min and max can be exceptionally handy when paired with the apply method:

function findMinAndMax(arr, type) {
  var result = [];
  arr.forEach(function(item) { return result.push.apply(result, item[type]); }, []);
  return { min: Math.min.apply(null, result), max: Math.max.apply(null, result) };
}

console.log(findMinAndMax(array, 'year')); // { minimum=1990, maximum=2010 }
console.log(findMinAndMax(array, 'value')); // { minimum=477790, maximum=7966277}

Check out this Fiddle for the code implementation.

Answer №3

With the latest update, Javascript has introduced a flatMap method for Array, which not only flattens an array of arrays into a single array but also applies a transforming function to each element:

var [min, max] = d3.extent(dataset.flatMap(d => d.value));

For demonstration:

var input = [
  { id: "AustraliaNewZealand", value: [477790,485825,487296,488885,502585,511718,526594,538967,550556,563572,577171,579126,591635,599216,604267,608954,615853,623685,618961,614920] },
  { id: "CentralEurope",       value: [1548736,1334452,1313088,1283248,1314709,1360546,1343907,1285511,1237278,1251872,1244069,1233778,1284639,1297510,1317861,1359787,1396681,1361445,1278731,1343044] },
  { id: "EasternEurope",       value: [4418516,3530464,3287987,2925644,2775181,2672238,2540975,2495036,2513372,2515375,2540796,2544848,2598148,2637682,2622241,2709974,2714204,2740248,2565213,2680226] }
];

var [min, max] = d3.extent(input.flatMap(d => d.value));

console.log(min);
console.log(max);
<script src="https://d3js.org/d3-array.v2.min.js"></script>

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

Center a span vertically inside a div as the text within the span grows to occupy the entire div

I am facing an issue with a table that has 25 td's. Each td contains specific elements as shown below: <td> <div> <span> text </span> </div> </td> Additionally, there is a script in place that adj ...

Manipulating CSS styles with jQuery

Trying to update the UL image in the CSS directory using jQuery for a Twitter stream: as tweets are displayed, want to change the avatar of the account associated with each post. Using .css is straightforward, but struggling to modify the URL for the new i ...

Why isn't my classList .add method working properly?

I've created a video slider background on my website, but I'm having trouble with the Javacript for video slider navigation. When I click on the button to change the video, nothing happens. The console is showing an error message that says "Canno ...

Validation using Joi allows for a field to be optional, but if it is included, it must be a positive integer

I am facing a challenge with a field in my JOI schema that I want to make optional, allowing for both undefined and null values. However, if a value is provided, it must be a positive integer. How can I accomplish this? So far, I have attempted the follow ...

Invalid index when trying to add to an array

I am currently faced with a challenge in modifying an array that I have at hand; +rows: array:31 [▼ 0 => array:2 [▼ 0 => "20190101" 1 => "5" ] 1 => array:2 [▼ 0 => "20190102" 1 => "15" ] ...

Developing an interactive Breadcrumb component using Vue.js in the latest version, Vue 3

Struggling to develop a dynamic Breadcrumb-Component in Vue.js 3. After hours of research, I haven't found a suitable solution due to outdated methods or lack of flexibility. As a beginner in frontend development, I am unsure about the best library to ...

Issue with Ajax form submission on one specific page

My form submission using JQuery AJAX is causing my page to redirect to submit.php instead of staying on the current page. I have tried various solutions but cannot pinpoint the issue... The PHP script seems to be working fine, with only one echo statement ...

Navigating through directory paths in JavaScript can be a daunting task for many

In my app.js file, I've included the following code: app.use(multer({dest:'./uploads'})) What does './uploads' refer to here? It is located in the same directory as app.js. In what way does it differ from simply using uploads? I ...

Transforming a value within a controller into a directive

I am uncertain if I am approaching this correctly, but my goal is to convert a piece of code from a controller to a directive. The reason for this change is that I want to reuse the code with different values without creating multiple large object literals ...

Exploring ways to locate a specific text within a URL using nodeJS

Here is a simple code snippet with a problem to solve: var S = require('string'); function checkBlacklist(inputString) { var blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"]; var found = false; for (var i = 0; i < b ...

Tips for creating a unit test for a React Component utilizing the useEffect hook and asynchronous fetch

Starting from a basic create-react-app setup, I am diving into the world of unit testing to enhance my skills. The goal is to update the main App component to fetch data from a local node API and display it as a string response. However, I'm encounter ...

Adjusting font size, contrast, brightness, and sound levels on a website with the help of jQuery

My client has a new requirement: adding functionality to increase font size, adjust contrast/brightness, and control sound on his website. When clicking on any of the control images, a slider should appear for the user to make adjustments accordingly. Ho ...

Having difficulty accessing any of the links on the webpage

I'm currently utilizing the selenium webdriver to automate a specific webpage. However, I am encountering an issue where my selenium code is unable to identify a certain link, resulting in the following error message. Exception in thread "main" org ...

The invocation of $.ajax does not work as a function

I'm encountering an issue when running npm start and trying to access the browser, I keep getting this error message in the stack trace. Error: $.ajax is not functioning properly at findLocation (G:\CodeBase\ExpressApp\routes\ind ...

Utilizing Angular's DomSanitizer to safely bypass security scripts

Exploring the capabilities of Angular's bypassSecurityTrust* functions has been a recent focus of mine. My objective is to have a script tag successfully execute on the current page. However, I keep encountering issues where the content gets sanitized ...

Modify the values of all cells within a specific column in a table by utilizing a 2D array for both rows and cells

https://codesandbox.io/s/1p770371j The demonstration above showcases a table where data can be modified in each cell, and the 2D array keeps track of which row and column the data changes occur. A new button has been added to the column header titles. Th ...

Fetching JSON data in NodeJS and rendering it in an EJS template

My goal is to read a JSON file and display it in an EJS file. Below is the code I am using: //server.js users = require('./controllers/users.js'); global.app_root = path.resolve(__dirname); app.get('/users', function(req, res) { ...

Guide on using jq to parse an array of JSON objects

I have a Json file that contains multiple arrays. Here is an example of the json source: { "iabVersion": "IAB_V2", "categories": [{ "categories": [{ "categories": [{ "id": "1.1.1", "name": "Commercial Trucks" } ...

Configuring Webpack for a React application with Express and Babel

I am in the process of developing a React application, utilizing React version ^15.6.1 along with Webpack, Express, Babel, and Yarn as the package manager. After successfully running the application, I am now preparing to transition it to production by co ...

Replicate the form to a new one while concealing the elements and then submit it

Initially, I was working with just one form. Now, I find myself in a situation where I need to utilize a different form which contains the same inputs. This is necessary because depending on the action taken upon submission, different processes will be tri ...