Generating ranges dynamically based on the values in an array

As I receive data from a server, my goal is to categorize it into various buckets for presentation.

The dataset appears in the following format:

Array [
  Object {
    "name": "1.00",
    "value": 17,
  },
  Object {
    "name": "1.01",
    "value": 10,
  },
  Object {
    "name": "1.5",
    "value": 9,
  },
  Object {
    "name": "1.20",
    "value": 8,
  },
  Object {
    "name": "1.30",
    "value": 7,
  },
  Object {
    "name": "0.80",
    "value": 5,
  }
 ]

In this context, the name represents the "size" and the value signifies the number of occurrences within the system. For example, there are 5 records with size "0.80" and 8 records with size "1.20".

The objective is to sort the data as follows:

[
{key: 'Under .30', value: 11}, 
{key: '.30 to .39', value: 3}, 
{key: '.40 .49', value: 2}, 
...
...
{key: '.90 to .99', value: 1}, 
{key: '1.00 to 1.09', value: 3}, 
{key: '1.10 to 1.19', value: 2}, 
...
...
{key: '5.00 to 5.09', value: 5},
{key: '5.00 to 5.09', value: 1},
...
{key: 'Over 10', value: 3},
{key: 'Other', value 21}
]

Here, the key denotes the size, while the value represents the total occurrences for that specific grouping.

Essentially, I aim to:

  1. Convert each row's name into a float value
  2. Determine if a range exists for this value based on its name
  3. If not, create the range and add the row's value to it
  4. If the range already exists, increment its value using the row's value

I am currently considering pre-creating all the arrays statically from 0.30 to 10+ and then iterating through them with multiple if statements, which would be over 100 cases.

Any assistance or alternative approaches to tackling this issue would be immensely appreciated!

Answer №1

To start, I would initiate a function that generates an array of conditions.

Based on the example provided,

the initial decimal value is 0.30 and increments by 0.10 until it reaches 10 and goes beyond 10.0.

function createConditions(startValue, endValue, increment) {
  let conditions = [
    {
      key: `Under ${startValue}`,
      value: 0,
      condition: (val) => val < startValue,
    },
  ];

  for (let i = startValue; i < endValue - increment; i += increment) {
    conditions.push({
      key: `${i} to ${i + increment}`,
      value: 0,
      condition: (val) => val > i && val < i + increment,
    });
  }

  conditions.push({
    key: `Over ${endValue}`,
    value: 0,
    condition: (val) => val > endValue,
  });

  return conditions;
}

let conditionsArray = createConditions(0.3, 3.0, 0.1);

Following this, you can create your set of conditions using the above function

const testData = [
  { name: "1.00", value: 17 },
  { name: "1.01", value: 10 },
  { name: "1.5", value: 9 },
  { name: "1.20", value: 8 },
  { name: "1.30", value: 7 },
  { name: "0.80", value: 5 },
];

This creates an array with keys, values, and conditions alongside another dataset from the server.

Iterate over the server data and apply the conditions. (This step could be encapsulated in a function where you pass the conditions array and data for processing – how you use it is up to you)

testData.forEach((datum) => {
  let find = conditionsArray.find((checker) =>
    checker.condition(parseFloat(datum.name))
  );

  if (find) {
    find.value += datum.value;
  }
});

Next, log the conditionsArray to review the outcomes.

console.log(conditionsArray.filter((ch) => ch.value > 0));
// display only conditions with values greater than 0 :)

Upon execution, the console displays the following:

[
  {
    key: '0.7999999999999999 to 0.8999999999999999',
    value: 5,
    condition: [Function: condition]
  },
  {
    key: '0.9999999999999999 to 1.0999999999999999',
    value: 27,
    condition: [Function: condition]
  },
  {
    key: '1.4000000000000001 to 1.5000000000000002',
    value: 9,
    condition: [Function: condition]
  }
]

For dealing with floating-point numbers in programming, check out

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

Show a button using CSS when the cursor is hovering

Expressing my gratitude to everyone! I need assistance with implementing a function in reactJS where the <button /> remains hidden during page loading and reveals itself when hovered over. Despite trying various methods, I have been unable to resolve ...

Guide to setting up a nested vuetify navigation drawer

I am facing a scenario where I have one fixed navigation drawer with icons and another dynamic navigation drawer that should open and close adjacent to the fixed one without overlapping. The current implementation is causing the dynamic drawer to overlap t ...

The function getComputedStyle('background-color') will return a transparent value that does not inherit from any ancestor element

When using getComputedStyle, it is expected to return the final computed CSS property value. However, for background-color, browsers tend to return "transparent" (or rgba(x,x,x,0)) instead of computing the inherited value from ancestors. The method only s ...

Using Jquery to toggle visibility and position of a button when clicked

I'm new to using Jquery and I've been able to create a button that shows a div and moves the button to the right when clicked. I have looked at similar questions about toggling visibility, but I also need to move the button back when it's cl ...

Learn the process of showcasing database content on a webpage with an interactive feature that enables users to choose and access additional details

Apologies if this question has been asked before, I have searched for a solution but my web development knowledge is limited. To better understand my issue, you can visit the site at 000freewebhost by following this link: In summary, I am trying to select ...

Learning how to access my CSS file using Express and Node.js

I am new to using express and node.js. I am trying to develop my app, but for some reason, my style.css file is not being recognized and I am unsure why. Initially, I attempted to use .scss files, but after researching, I discovered that it was not possi ...

When using jQuery to parse JSON, I am unable to make changes to an array

inventory = new Array(); $.getJSON('items.php', function(data){ $.each(data , function(i,jsonData) { inventory[1] = "item"; }); }); alert(inventory[1]); This code is supposed to display the items in the inventory, but it's ...

The system encountered an error stating that there is no defined method for 'id' within the ActiveRecord Associations CollectionProxy of the Page object

I'm puzzled by a query I'm running in Rails console. My Rails version is 4.1.5. To start, I retrieve a group of items: pages = Item.item_steps.map {|item| item.pages } After getting these pages, I check their class: pages.class #array So, now ...

Obtaining a subset of data from firebase

I am currently working on retrieving a sub-collection from the Firestore database using Angular. In my database, I have a collection called 'Company' which contains fields for 'Name' and 'Id', as well as a sub-collection named ...

Rendering a dynamic 3D model with animated sequences in Three.js through CreateFromMorphTargetSequence

When attempting to load a GBL file and play the animation, I encountered the following error message: TypeError: Cannot read property 'length' of undefined at Function.CreateFromMorphTargetSequence function Animate() { if(window.anim_flag) ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

The Vue user object appears to be null in spite of being defined and clearly visible in the log output

There seems to be an issue with my function that utilizes a person's user name to retrieve the current User from the database. Initially, when I log the current user within the function, everything works perfectly. However, once I attempt to access it ...

Output the value of each key from an array only if the corresponding key in a second array

There are two arrays at play: $choices = array ( [model] => 3D Modeling / BIM [edb] => Engineering & Design-Build [gse] => Green & Sustainable Energy [ipd] => Integrated Project Design [lc] => ...

Can an input element be used to showcase a chosen image on the screen?

I would like to display the selected image from an input element. Can this be done with a local file, accessing the image on the client side, or do I need to upload it to a server? Here is my React code attempt: I can retrieve the correct file name from t ...

Creating a Circle with Pixi.js v4 and Typerscript in IONIC 2

I have been attempting to create a custom class in TypeScript that utilizes PIXI.js to draw circles. Below is the code for my home.ts class: import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'i ...

Issue with data entry: unable to enter the letter 'S' in search field

This bug has been a real challenge for me. It's strange, but I'm unable to type the letter "S" into the search input field. Oddly enough, the keyboard seems to be functioning properly. Please find the sandbox below for reference: https://codes ...

Removing an item from an array containing several objects

I have an array that looks like this: var participants = [ {username: "john", time: null}, {username: "samira", time: null}, {username: "mike", time: null}, {username: "son", time:null} ] To remove an item based on the username, I can do the f ...

Mongoose encountered a RangeError due to exceeding the maximum call stack size

I need to bulk insert documents into MongoDB using the native driver instead of Mongoose to enhance the writing speed. Mongoose does not support bulk insert of an array of documents, prompting me to bypass it. However, I encountered the "RangeError: Maxim ...

CSS ID selectors are not functioning properly

In my React.JS project, I am working with a div that contains a button and a list. The list is specifically identified by the id "results". return <div> <Button label="Combine Cards" disabled={!this.props.combineReady} onClick={this.handleCli ...

Vue.js and axios causing an empty array after the page is refreshed

As a newcomer to coding and using vue cli, along with my limited English skills, I apologize if I am unable to articulate the issue clearly. However, I am reaching out to the community for assistance. The code snippet below is from store.js where I fetch ...