How can I generate an incidence array using randomly generated array elements?

Considering the following:

var dataset = [
   {X: 0, Y: 0, ApiKey: "Something"},
   {X: 100, Y: 0, ApiKey: "Something"},
   {X: 1500, Y: 200, ApiKey: "Something"},
   {X: 1600, Y: 850, ApiKey: "Something"},
   {X: 0, Y: 750, ApiKey: "Something"},
   {X: 0, Y: 800, ApiKey: "Something"},
];

I'm in need of generating a new array to demonstrate the number of incidents within specific ranges:

var output = [
  {fromX: 0, ToX: 500, incidents: 4},
  {fromX: 1500, ToX: 2000, incidents: 2}
];

I came up with an iterative approach, but the processing time goes up to 8-12 minutes when the dataset contains 15000 objects in Node.js. Does anyone have any suggestions for a more efficient solution?

Answer №1

You can establish intervals and utilize a hash table to track the interval calculated alongside its count.

var dataSource = [{ X: 0, Y: 0, ApiKey: "Something" }, { X: 100, Y: 0, ApiKey: "Something" }, { X: 1500, Y: 200, ApiKey: "Something" }, { X: 1600, Y: 850, ApiKey: "Something" }, { X: 0, Y: 750, ApiKey: "Something" }, { X: 0, Y: 800, ApiKey: "Something" }],
    interval = 500,
    grouped = [];
  
dataSource.forEach(function(a) {
    var key = Math.floor(a.X / interval);
    if (!this[key]) {
        this[key] = { fromX: key * interval, toX: (key + 1) * interval, incidence: 0 },
        grouped.push(this[key]);
    }
    this[key].incidence++;
}, Object.create(null));

console.log(grouped);

Employing intervals for X and Y.

var dataSource = [{ X: 0, Y: 0, ApiKey: "Something" }, { X: 100, Y: 0, ApiKey: "Something" }, { X: 1500, Y: 200, ApiKey: "Something" }, { X: 1600, Y: 850, ApiKey: "Something" }, { X: 0, Y: 750, ApiKey: "Something" }, { X: 0, Y: 800, ApiKey: "Something" }],
    interval = 500,
    grouped = [];
  
dataSource.forEach(function(a) {
    var keyX = Math.floor(a.X / interval),
        keyY = Math.floor(a.Y / interval),
        key = keyX + '|' + keyY;
    if (!this[key]) {
        this[key] = {
            fromX: keyX * interval,
            toX: (keyX + 1) * interval,
            fromY: keyY * interval,
            toY: (keyY + 1) * interval,
            incidence: 0
        },
        grouped.push(this[key]);
    }
    this[key].incidence++;
}, Object.create(null));

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you're looking to improve performance in your code, I suggest considering D3 for its optimization features like groupby.

d3.group()
    .key(_ => _)
    .rollup(leaves => leaves.length)
    .entries(sourceData.map(_ => _.Y / 1500 | 0))
    .map(_ => { return {
        'startY': _.key * 500,
        'endY': (1 + _.key) * 500, 
        'frequency': _.values
    }})

Answer №3

To enhance the functionality, consider expanding the dataSource array. Whenever a new instance is added to the dataSource, it will be documented for future reference.

dataSource = [];
dataSource.ix = [];
dataSource.result = [];
dataSource.push = function(obj) {
    if (ix[obj.X] !== undefined)
        ix[obj.X]++;
    else ix[obj.X] = 1;
    Array.prototype.push.call(this, obj);
};
dataSource.calculate = function(start, end) {
    var index, result = {
        fromX: start,
        ToX: end,
        incidence: 0
    };
    for (index = start; index <= end; index++) {
        if (this.ix[i])
            result.incidence += this.ix[index];
    }
    this.result.push(result);
};

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

Utilizing WordPress to dynamically update the footer content on a targeted webpage by modifying the HTML/PHP/JS code

Let me provide some clarity. Details: - Website built on WordPress This website is bilingual with Hebrew and English languages. The issue is with the footer section. I have 4 lines that need to display: - Address: ........ - Phone: ....... - Fax: ...... - ...

The jQuery click event is failing to trigger

I am facing an issue with some buttons that have specific classes. Here is an example: https://i.sstatic.net/CVIR2.png Each of these buttons contains JSON data stored in a data attribute. I have created a function to detect when a button is clicked and p ...

activate the bootstrap popover by double-clicking instead of a single click

Clicking on a certain div triggers a popover to display another div, which works initially. However, once the popover is removed by clicking outside the div, it requires two clicks to trigger the popover again. How can this be fixed so that it always works ...

What is the best way to determine which user is currently logged in to a Linux system?

Understanding the user on whose behalf the program is operating is crucial. If it's running as root, proceed with code execution. If it's a regular user, execute the bash command through a child process. ...

What is the best way to display text from one text field onto another text field?

Here's a challenging question that I've been pondering... Issue: I am using a virtual keyboard that needs to interact with different text fields on various pages. Every time I click on a text field, the keyboard should appear, and every key I pr ...

Setting compilerOptions.isCustomElement for VueJS 3 in a Laravel project: A step-by-step guide

I am currently working on integrating VueJS 3 into a Laravel project and utilizing a JS file to implement a markdown toolbar. The JS file contains functions that generate buttons for applying various markdown options. Everything is functioning properly, bu ...

A command-line style text input box in HTML

I am currently developing a unique text box that enables the execution of custom commands using a customized syntax. This concept is intended to help teach programming to children. For example, when a user types a $ sign, the program responds with an aler ...

Using Conditional Rendering and ReactCSSTransitionGroup for Dynamic Animations

I have developed a small application that displays different components based on a Redux state. I am trying to add a "fade" animation when one of the components renders, but unfortunately, it is not working as expected. Here is my current setup: content.j ...

Nodemailer is experiencing difficulties when used within the routes directory

Recently, I encountered an issue with my subscribe form. It functions perfectly when called from app.js where the express server is defined. However, when I move subscribe.js to the routes folder and connect both files, it fails to send emails. Upon pressi ...

Error: Unable to locate script file with npm installation of AngularJS

After installing Angular using npm, I added the following script to my public/index.html file: <script src="/node_modules/angular/angular.js"></script> However, I am encountering a 404 error in the Chrome console. Does anyone have any suggest ...

How to simultaneously update two state array objects in React

Below are the elements in the state array: const [items, setItems] = useState([ { id: 1, completed: true }, { key: 2, complete: true }, { key: 3, complete: true } ]) I want to add a new object and change the ...

Express.js never terminates a session

I have a Backbone View that makes an Ajax call to the server to delete a session. Upon triggering the following event on the server: app.delete('/session', function(req, res) { if (req.session) { req.session.destroy(function() { ...

Exploring the potential of Bootstrap/bootflat and jQuery progress bars

I am attempting to display and animate a progress bar while loading an HTML page into a div using jQuery. The progress bar I am using is from Bootstrap (Bootflat) and has the following structure: <div class="progress" style="visibility:hidden;"> ...

When using Node.js, res.render may encounter issues, but res.send typically functions properly

Currently, I am in the process of setting up the environment for a node.js app. Unfortunately, I am encountering an issue where the views/ejs files are not being rendered properly. When I use the following code snippet: app.get("/", function(req, res){ ...

The validation for the number input step in HTML does not function properly when using the value property

Currently working on a form that requires users to input numbers with up to two decimal points, such as valid money amounts. Utilizing Next.js (React) as the JavaScript framework for this project. Encountered an issue where entering a number with more tha ...

Scanning barcode and Qrcode with Angular js HTML5 for seamless integration

Looking to scan Barcode and Qrcode on Android, iPhone, and iPad devices for a project that is built on AngularJS and HTML5 as a mobile website. The requirement is not to download any third-party native application on the device, ruling out the use of nati ...

Ways to categorize items retrieved from an HTTP request to the backend in Angular

When making a call to the backend using this http request: this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/)).subscribe(values => { this.studentObject = values; }); The studentObject is structured as shown below: { recor ...

Patiently awaiting the completion of the entire page loading process

When using the methods below, we can determine if the entire page has finished loading. Sys.sleep(5) or remDr$executeScript("return document.readyState == 'complete';") or remDr$setTimeout(type = "page load", milliseconds = 10000) However, ...

My website code being stored in cache by Chrome (as well as other browsers)

Issue: I am facing an issue with hosting a widget on my client's website where the widget needs to be different for each page. To display the widget, the client embeds a script tag on their pages. This script is loaded on every page and the content ...

Execute unit tests for the nodejs project

Looking to execute the tests for this project on GitHub? Head over to the test folder on https://github.com/node-opcua/node-opcua. However, I'm unsure about the testing framework that was utilized and how to run all the tests. Any guidance would be mu ...