Creating balanced numerical values within the range of 0 to 1 using an array

Is there a way to create a set of numbers between 0 and 1 that is proportional to an array of sales with varying sizes?

For instance, if the sales values are [1, 80, 2000], would it be possible to generate an array like [0.1, 0.4, 1]?

Answer №1

a fresh take on problem-solving:

var numbers = [1, 80, 2000] ;

numbers.map(function(num){
   return num / this;
}, Math.max.apply(0, numbers) );

//==[0.0005, 0.04, 1]

i believe there was a miscalculation in the original post...

edit: explanation of the process:

  1. determine the largest number in the array
  2. calculate each array element as a fraction of the largest number

For the first step, JavaScript's Math.max function is used. To apply a function with array arguments, the apply() method is utilized with 0 as the context, although it's actually not used; it just needs to be something present.

In the second step, each element is compared to the largest number from step #1 using the Array.map method to iterate through the array and perform an operation on each element. By passing the largest number as "this" to Array.map(), the need for a performance-degrading function closure is avoided.

Answer №2

Uncertainty surrounds the connection between the original array and the resulting array. It is assumed that the goal is to determine what fraction each item represents of the total sum (proportion):

Consider the following solution:

function calculateProportions(arr){

    //calculate the total sum
    var total = 0;
    for(var i=0; i<arr.length; i++)
        total += arr[i];

    //store the proportions with high precision in a new array
    var newArr = [];

    for(var j=0; j<arr.length; j++)
        newArr.push((arr[j]/total).toFixed(2));

    console.log(newArr);
    return newArr;
}

To use the function, do the following:

var values = [5, 120, 750];
calculateProportions(values);

Check out this example

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

The correct method for sending an array to a shader in three.js

In my current project, I have a straightforward program in which I am attempting to pass an array of predefined values (essentially serving as a lookup table) to a shader. The corresponding code snippet looks like this: var table = []; for ( var ...

Tips for displaying only one item from an array in the output

Looking for a way to display only the elements of an array in the output from a document? Here's an example: { _id: ObjectId("5effaa5662679b5af2c58829"), email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60050d01090c ...

PHP makes it simple to decode JSON into an associative array, complete with numbering for

I am working with JSON data that is dynamically generated by SimpleXML from an XML file: "{"description":"Testing","site":"http:\/\/localhost","steps":{"step":[{"command":"grabimage","parameter":"img[alt=\"Next\"]"},{"command":"click", ...

Changing global properties in VueCli

Recently, I integrated a component library into my Vue 3 project. All instances of the component require the same styles. Instead of manually adjusting each instance's props, I opted to utilize a global property: app.config.globalProperties.$tooltipS ...

Guide on extracting HTML content from JSON and displaying it in a UIWebView (utilizing Swift 3.0)

Can anyone guide me on how to use JSON2HTML to parse HTML data from JSON and display it in an UIWebView using Swift 3.0? Your help is much appreciated! This is what I have attempted so far: let jsfile1 = try!String(contentsOfFile: Bundle.main.path(forRes ...

What could be causing a NullPointerException when attempting to populate an array?

I'm currently working on a task that involves populating an array of BitSets with information from an integer array. //ar is a SIZE*SIZE 1-D int array, SIZE is defined as a constant //declare BitSet array BitSet bs[] = new BitSet[SIZE]; ...

When you drag down on mobile Safari on an iPad, touch events may cease to fire in HTML5

When I implement event listeners to handle touch events like touchmove and touchstart document.addEventListener("touchstart", function(event){ event.preventDefault(); document.getElementById("fpsCounter").innerHTML = "Touch ...

Retrieve JSON data from a PHP script to be used in an Angular scope

I am attempting to retrieve JSON data from a PHP file to use in an Angular controller. I have used json_encode(pg_fetch_assoc($result)); within the PHP file and when I check with console.log($scope.contents); in the Angular controller, the JSON data is ret ...

Error: The method _firestore.default.initializeApp is not defined as a function

I am encountering an issue in my app where "_firestore.default.initializeApp" is not recognized as a function while evaluating src/screens/Login.js, src/appNavigator.js, and App.js. I have already ensured that I have added the firebaseconfig and connected ...

React and Express are two powerful technologies that work seamlessly

Here lies the contents of the mighty index.html file <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <s ...

Using Javascript arrays to assign values to a Json object in CanvasXpress

I'm seeking advice on the best source for assistance with CanvasXpress. I haven't found any relevant threads in the forum yet. Currently, I'm using CanvasXpress to showcase dynamic data and I know that it accepts json objects. My issue arise ...

drawing tool with JavaScript and HTML5

Can you help me figure out why my sketchpad isn't working in Processing.js? I've checked my code and there are no errors, but the canvas is not showing up. Any suggestions? Take a look at the code below: function createSketchPad(processing) { ...

What is the best way to format a condensed script into a single line?

There are times when the script in the web browser is packed into one line like function a(b){if(c==1){}else{}}. I have attempted to locate something that would display it in a more normal format. function a(b) { if(c==1) { } else { } } Howev ...

Merge JavaScript Functions into a Single Function

I am looking to streamline the following javascript code into a single function by utilizing an array of ids instead of repetitive blocks. Any suggestions on how to achieve this would be greatly appreciated. Currently, in my code, I find myself copying an ...

Disable location prompt feature when using AngularJS with Maps API

For my web application, I developed a feature that includes a map with custom markers using Angular loops: <map data-ng-model="mymap" zoom="4" center="[38.50, -95.00]" style="heigth:375px"> <div ng-repeat="item in list"> <marker pos ...

When my webpage is opened in Firefox, I notice that it automatically scrolls down upon loading

I recently embarked on the task of building a website from scratch but ran into an unusual bug in Firefox. The issue causes the page to scroll down to the first div, completely bypassing its margin. I want to clarify that I am not seeking a solution spe ...

Typing should be positioned on either side of the declaration

When I define the type MyType, it looks like this: export type MyType = { ID: string, Name?: string }; Now, I have the option to declare a variable named myVar using three slightly different syntaxes: By placing MyType next to the variable ...

The left-hand operator in Typescript is not valid

I am a beginner in typescript and I have been following a tutorial called Tour of Heroes on Angular's website. In the final chapter of the tutorial, when I tried to use HTTP with the provided code, everything seemed to run fine but I encountered an er ...

The jQuery code does not execute following the use of window.location.replace( url ) command

I'm facing an issue with my code that involves redirecting the page to the index page after clicking on a specific link ('#versionPageFromProdLink'). The index page contains certain content within a div, which I want to hide once the redirec ...

Acquiring an alternative data structure in JavaScript or JSON

When clicking on a div with different attributes, I am attempting to retrieve a data object. Here is an example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var locA = { "fro ...