Home > other >  How to bucket JSON data for a range?
How to bucket JSON data for a range?

Time:10-15

I'm new to programming so appreciate any help and patience here. :)

We have some data that we're trying to sort by buckets (days of the month in this case) to create smaller sets of data like so:

export const Weather = [
  {
    city: "STL",
    month: "july",
    daysbucket: "1 to 10",
    percentages: {
      sunny: "45.5",
      rainy: "20.5",
      cloudy: "10.8",
      partlycloudy: "23.2",
    },
  },

Is there a better way than using string like daysbucket: "1 to 10"?

The idea is to run some forecast simulations using a probability function that pulls the percentage of the past weather for a certain day without having to list these percentages for each day of the month. So far I planned to get the day of the month and then do some if statements to slot it into a string for 1-10, 11-20, etc. but wanted to see if there was a better way before I get too far. I have several data sets with a variety of buckets stored as strings but I also have control over the data so can change it as needed. All of the data is stored in MongoDB. Thanks in advance!!!

CodePudding user response:

To be able to make calculations and comparisons with the daysbucket better to defined it like this:

export const Weather = [
  {
    city: "STL",
    month: "july",
    daysbucket: {
      from: 1,
      to: 10 
    },
    percentages: {
      sunny: "45.5",
      rainy: "20.5",
      cloudy: "10.8",
      partlycloudy: "23.2",
    },
  },

Having this structure you can compare it like:

if (day > daysbucket.from && day < days bucket.to) { ... }

And so on, note that the in order to compare numbers the values should be defined as numbers, not strings, or if string you need to convert them to numbers (use parseInt() or Number())

CodePudding user response:

I would use an object to do that. Something like :

daysbucket: {
min:1,
max: 10
}
  • Related