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

Adding dots between page numbers when using ReactJS/Javascript Pagination can be achieved by implementing a specific method

I have created a pagination component using React JS. Currently, it only displays all the page numbers, but I want it to show dots when there are more than 8 total pages. Here's how I envision it: c. When total is less than 9 pages: Page 1 selecte ...

What distinguishes running rm -rf node_modules + npm i from using npm ci?

When using a Unix system and needing to clean out the node modules folder, is there any benefit or distinction between executing rm -rf node_modules followed by npm i as opposed to npm ci My understanding is that both yield the same outcome, but is th ...

Unexpected outcomes in linq.js

Hey there, I have a JSON object named "Faults" that looks like this: "Faults":[{"RoomId":1,"ElementId":173,"FaultTypeId":1,"Count":1,"Remark":""},{"RoomId":3,"ElementId":211,"FaultTypeId":7,"Count":1,"Remark":""},{"RoomId":4,"ElementId":173,"FaultTypeId": ...

How to Share Your Vuejs Component with the World by Publishing it on npm

I have recently developed a Vue.js 2 project using webpack which consists of 2 components. My goal is to share this project as an npm package so that the components can be easily reused in multiple projects. After publishing the project on npm with npm pu ...

Pressing the enter key within Material UI Autocomplete will allow you to quickly create new

Wouldn't it be great if Autocomplete in material ui could do this: wertarbyte Imagine being able to insert text (string) without the need for a list of elements to select from. This means that the noOptions message shouldn't appear, and instead ...

Using JavaScript variables within the value section of a JSON is a common requirement for developers

var averageTemperature = req.params.rating; var destinationName = req.params.name; var query = { "results.name": destinationName }; var updateQuery = { $set: { "results.$.rating": averageTemperature } }; mach.update(query, updateQuery, function(err, res ...

Retrieve the quantity information from a JSON object

Hello everyone! I am new to programming and need help. How can I retrieve the 'qty' value of 0 using JSON and PHP from the following data: {"XXXXXX":[],"XXXXXX":[],"total":[{"assetref":"","qty":0,"raw":0}]} I have attempted the following code: ...

How to message someone privately in a public Discord channel using discord.js

Can someone help me figure out how to create a message in discord.js version 12.5.3 that only I can see? I know how to send messages to channels using message.channel.send, but I'm not sure how to make a message visible only to myself. Thank you! ...

Standardizing JSON data with irregularly structured nested arrays/objects using pandas

Recently I encountered an issue while using pandas' json_normalize with a specific JSON file, similar to the problem discussed in this thread: https://github.com/pandas-dev/pandas/issues/37783#issuecomment-1148052109 The challenge lies in extracting ...

I would greatly appreciate your assistance in deciphering the JavaScript code provided in the book "Ajax in Action"

While reading through the Ajax in Action book, I came across a code snippet that has left me with a couple of questions. As someone who is new to web programming and still getting to grips with JavaScript, I am hoping for some clarity on the following: ...

Issue with submitting input fields that were dynamically added using jquery

I created a table where clicking on a td converts it into an input field with both name and value. The input fields are successfully generated, but they do not get submitted along with the form. In my HTML/PHP : <tr> <f ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...

Issues with JavaScript Content Loading in epub.js on a Website

Hey there, I'm currently experimenting with the epub.js library and trying to set up the basics. However, I'm encountering an issue where the ebook is not showing up in my browser: <!DOCTYPE html> <html lang="en"> <head&g ...

Mobile application for Android that utilizes JSON technology

I am currently working on developing an Android app and have encountered a problem. I have an API and need to write its data to a file. This is the code snippet for writing: string url2 = "http://new.murakami.ua/?mkapi=getProducts"; JsonValue j ...

Simultaneously updating the states in both the child and parent components when clicked

In my code, I have two components: the parent component where a prop is passed in for changing state and the child component where the function is called. The function changes the state of the parent component based on an index. changeState={() => this ...

"Error: Unable to determine the type id during the deserialization process" encountered while attempting to deserialize a subclass

I am currently working on integrating JsonSubTypes into my project and I would like to implement a graceful handling mechanism for unrecognized subtypes. The version of Jackson that I am using is 2.9.7, and upgrading is not an option due to dependencies on ...

Experiencing an anonymous condition post onChange event in a file input of type file - ReactJS

When using the input type file to upload images to strapi.io, I noticed that an unnamed state is being generated in the React dev tools. Can someone explain how this happened and how to assign a name to that state? state constructor(props) { super(pro ...

What is the process for retrieving the chosen country code using material-ui-phone-number?

When incorporating user input for phone numbers, I have opted to utilize a package titled material-ui-phone-number. However, the challenge arises when attempting to retrieve the country code to verify if the user has included a 0 after the code. This infor ...

What is the best way to transfer properties to a different component using the onClick event triggered by an element generated within the map function?

I am currently working on an application using react to retrieve data from a mongodb database. Within one of the components, called Gallery, I have integrated a map function to display a list of items. My goal is to implement an onClick event for each elem ...

Effortless pagination across various pages, utilizing diverse CSS selectors

I've integrated simple pagination into my website, but I've encountered a issue. My navigation consists of CSS tabs, each holding a unique pagination component. Here is the jQuery pagination code snippet: $(function(){ var perPage = 8; var open ...