JavaScript implementation of the results sorting

I have 2 sql queries to calculate the turnover for each semester.

Results from query 1:

{
  "LRU": [
    "RADOME",
    "RADOME",
    "ATSU",
    "MFC",
    "FWC",
    "Unspecified",
    "AZE",
    "ECP",
    "CMM",
    "ECP"
  ],
  "Client": [
    17346,
    17512,
    7262,
    17242,
    4001,
    17164,
    7277,
    17334,
    8059,
    300015
  ],
  "round": [
    -33250,
    -13358,
    -11731,
    -10506,
    -6005,
    -3132,
    -2448,
    -2369,
    -2236,
    -2074
  ]
}

Results from query 2:

{
  "LRU": [
    "RADOME",
    "RADOME",
    "ECP",
    "PRIM",
    "MFC",
    "FWC",
    "RCI",
    "TAV",
    "CAL",
    "ECP"
  ],
  "Client": [
    17223,
    17346,
    7262,
    7956,
    594,
    4001,
    7277,
    17260,
    347,
    8059
  ],
  "round": [
    -34276,
    -33250,
    -11731,
    -6273,
    -5684,
    -4200,
    -2723,
    -2586,
    -2510,
    -2236
  ]
}

I created a javascript function to calculate the average variation between the 2 queries, sort them, and identify the top 10 customers with increased turnover and the bottom 10 customers with decreased turnover.
Here is my function:

    var query1 = {{repair_semester1}};
var query2 = {{repair_semester2}};
var data = {};
[query1, query2].forEach(function (query, semester) {
    query.Client.forEach(function(clientId, index) {
        var client = data[clientId] = data[clientId] || {};
        var clientArt = client[query.LRU[index]] = client[query.LRU[index]] || [0, 0];
        clientArt[semester] = query.round[index];
    });
});

// Now report on that data
var output = [];

for (client in data) {
    for (article in data[client]) {
        var turnovers = data[client][article];
            output.push(formatName(client,article,turnovers));
        }
}

function formatName(client, article, turnover, a) {

    return("Client: " + client + ", LRU.: " + article 
                  + ", semester t/o: " + turnovers
                  + " " + (turnovers[0] === 0 ?
                                       turnovers[1] : 
                              ((turnovers[1]-turnovers[0]) /turnovers[0])*100

        ));

}

percent.sort(function (a, b) {
    return b.percent - a.percent;
});

return("top", percent.slice(0, 10));
return("bottom", percent.slice(-10));    
return(output);

Here are some sample results:

  {
  "output": [
    "Client: 347, LRU.: ECP, semester t/o: 0,-2510 -2510",
    "Client: 394, LRU.: ATSU, semester t/o: 0,10433 10433",
    "Client: 394, LRU.: FCPC, semester t/o: 0,3023 3023",
    "Client: 417, LRU.: FWC, semester t/o: 0,17683 17683",
    ...
   ]
}

Please help me correct the function to determine the customers with the highest and lowest turnover variations along with their corresponding LRUs. Thank you.

Answer №1

This strategy is centered around the provided objects and aims to achieve the desired outcome by utilizing an object that possesses the necessary properties, arranging it based on percentage.

In order to extract the top 10 percent values, the array is sliced and a new array is generated, which is then analyzed to obtain the desired information in string format. This process is similarly applied for the bottom 10 percent values.

function formatName(o) {
    return "Client: " + o.client + ", LRU.: " + o.article + ", semester t/o: " + o.turnovers + " " + o.percent;
}

var query1 = {
        LRU: ["RADOME", "RADOME", "Unspecified", "Unspecified", "Unspecified", "Unspecified", "Unspecified", "ECP", "ECP", "ECP"],
        Client: [17346, 17512, 7262, 17242, 4001, 17164, 7277, 17334, 8059, 300015],
        round: [-33250, -13358, -11731, -10506, -6005, -3132, -2448, -2369, -2236, -2074]
    },
    query2 = {
        LRU: ["RADOME", "RADOME", "Unspecified", "PRIM", "Unspecified", "Unspecified", "Unspecified", "ECP", "ECP", "ECP"],
        Client: [17223, 17346, 7262, 7956, 594, 4001, 7277, 17260, 347, 8059],
        round: [-34276, -33250, -11731, -6273, -5684, -4200, -2723, -2586, -2510, -2236]
    },
    data = {},
    output = [],
    max,
    min,
    client,
    article,
    turnovers;

[query1, query2].forEach(function (query, semester) {
    query.Client.forEach(function (clientId, index) {
        var client = data[clientId] = data[clientId] || {};
        var clientArt = client[query.LRU[index]] = client[query.LRU[index]] || [0, 0];
        clientArt[semester] = query.round[index];
    });
});

for (client in data) {
    for (article in data[client]) {
        turnovers = data[client][article];
        output.push({ client, article, turnovers, percent: turnovers[0] === 0 ? turnovers[1] : (turnovers[1] - turnovers[0]) * 100 / turnovers[0] });
    }
}

output.sort(function (a, b) {
    return b.percent - a.percent;
});

max = output.slice(0, 10); // get top 10
min = output.slice(-10);   // get bottom 10

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

Answer №2

The function called formatName requires 4 parameters to work correctly:

function formatName(client, article, turnover, a) 

However, you are only providing 3 parameters when calling it:

output.push(formatName(client, article, turnovers));

Attempting to use the fourth parameter will not be successful. You need to either make the parameter optional and check if it is set or ensure that you pass all required parameters each time you call the function.

EDIT: Upon further review, errors have been identified from before.

  • The variable 'data' is defined as an object instead of an array, making it impossible to push variables into it or iterate over it.
  • In your initial loops, you are creating variables but failing to push them into the data array. Make use of data.push(key, value).

When executing this line:

var client = data[clientId] = data[clientId] || {};
, you are simply assigning the value of an empty variable 'client' with the value of 'data[clientId]' which is also empty.

  • Furthermore, there is no sorting function present to sort the output. Your sort function only performs subtraction.
  • Lastly, your syntax appears confusing with returns outside of functions.

These are the main issues within the code. Correcting these mistakes should yield better results.

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

Retrieve information from a form in AngularJS without relying on two-way data binding

Utilizing two-way data binding, the code operates effectively. However, there is a stipulation - instead of using =, use <. Upon the initial launch of the application, the text inputs will contain predefined values. The objective is to enable users to ...

Storing knockout view model data in a database and fetching it back

I am currently working on a web form that utilizes knockout, and I need to add a new feature that allows users to save the form as a draft in the database. Later on, they should be able to load it again to make modifications or submit it. Is there a built ...

Displaying an image in AngularJS using a byte array received in the response

Dealing with a service that adds properties to a file and returns it as a byte array in the response. I'm struggling to display it properly since it's in byte form. Attempted converting it to base64 but still showing raw bytes. PNG IHDR&L ...

Activate lighting in Three.js with a simple click

I successfully loaded a sphere mesh with Lambert material. Now, I am trying to add a light source to the point where there is an intersection after clicking. target = object that was clicked. to = vector3 of my click. When the dblclick event listener is ...

The phenomenon of an invisible Absolute or relative position leading to grid components overlapping in Next.js

I've been struggling with this issue for over 48 hours now. I've attempted to troubleshoot by commenting out everything except the affected components and even swapping entire components around, but the problem persists. Oddly enough, rearranging ...

My objective is to show the div element just once using AngularJS

Here's the scenario I want to show this div just once, not multiple times: //angular js code $scope.arr=["sunday","mpnday","tuesday"]; //html view <ul> <li ng-repeat="x in arr"> <div><p>{{ x }}</p> </div> & ...

What is the method for obtaining the properties of a type as an array in Typescript?

In the given scenario: class Foo { constructor( private one: string, private two: string, private three: string) { } } Is there a way to create an array containing the type's properties? For example, I need to gene ...

Is there a way to enable Tail Recursion Optimization in TypeScript?

const isPositive = (n: number) => n > 0; function fitsIn(dividend: number, divisor: number, count: number, accum: number): number { if (accum + divisor > dividend) { return count; } return ...

Give a jQuery Mobile flipswitch a new look

Currently, I am using jQuery Mobile and recently attempted to refresh a flipswitch. However, upon executing the code $("#flipEnabled").slider("refresh");, I encountered an error in the console: Uncaught Error: cannot call methods on slider prior to initial ...

Steady Content of a Parallax Webpage

Hey there! I recently put together this awesome site and I'm facing a challenge with fixing text on the first slide, specifically the one featuring the Nike basketball. Right now, the text 'The first of its kind' is part of the background im ...

Issues encountered when selecting table data for filtering

One issue I am facing is with my HTML table that contains a lot of data. I have created a select option to filter the table and display the filtered data. The select options are based on the "route" column, with only three options available: Marikina, Mont ...

Tips for customizing your MUI slider design

import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; function valuetext(value) { return `${value}°C`; } export default function RangeSlider() { const [value, se ...

Deactivating one div's class upon clicking on another div

Below is the HTML code snippet: <div class="container"> <ul class="navbar"> <li class="nb-link"><a>Home</a></li> <li class="dropdown"> <a>CBSE</a> <ul class="dropdown-menu"&g ...

What is the best way to show an on/off button in an HTML page when it loads, based on a value stored in a MySQL database?

Is there a way to display a toggle button onload based on a value from a MySQL database table? I need the button to switch between 0 and 1 when clicked. I've looked at several solutions but none of them seem to work for me. Any help would be greatly a ...

Failed commitments in Protractor/WebDriverJS

WebdriverIO and Protractor are built on the concept of promises: Both WebdriverIO (and as a result, Protractor) APIs operate asynchronously. All functions return promises. WebdriverIO maintains a queue of pending promises known as the control flow to ...

Small-scale vue iterates through elements with v-for but fails to display them

I'm really interested in Petite-vue, but I've been struggling to get even the basic functionalities to work. Unfortunately, there isn't a lot of examples or tutorials available online for petite-vue. Can anyone suggest good resources? Right ...

Utilizing util.format to enclose every string within an array with double quotation marks

Currently .. var utility = require("utility"); var carsInput = 'toyota,chevrolet'; var cars = carsInput.split(','); var queryString = utility.format('Cars: [%s]', cars); console.log(queryString); // Cars: [toyota,chevrolet] ...

Issues arising from the event target

What is the reason behind this code functioning successfully only when the alert function is called? The color changes after closing the alert box, but if the line with the alert command is commented out, nothing happens. function setLinkColor(el) ...

The Ajax page does not respond to click events when the function is declared within $(function(){ }) block

Create two functions as shown below: <script> $(function () { function myFunctionB() { alert("ddd"); } }) function myFunctionA() { alert("ddd"); } </sc ...

Is there a way to use fetch() to automatically redirect a user after logging in?

I'm currently working on a node.js application using express, and I am in the process of creating a login form for my users. I want to include a Javascript file that utilizes fetch() to send a POST request to my API for user authentication. However, I ...