Steps for transforming a numerical value into an array with individual elements, such that the maximum value in the array will be 1

Can someone assist me?

I have a value of 4.8 (it represents a rating of 4.8/5).

Now I want to convert it into an array with the following structure:

[1, 1, 1, 1, 0.8]

What I mean is that the value should be split into 5 elements, with each element not exceeding 1.

Here are some more examples:

2.8 should be [1, 1, 0.8, 0, 0]

0.5 should be [0.5, 0, 0, 0, 0]

5 should be [1, 1, 1, 1, 1]

3 should be [1, 1, 1, 0, 0]

and so on...

let number = 4.8;

Answer №1

To implement the Array.from() method with a length of 5, you can calculate the minimum value between 0 and the difference between the number and the index (num - i), or 1:

const generateArray = num => Array.from({ length: 5 }, 
  (_, i) =>  Math.max(Math.min(num - i, 1), 0)
)

console.log(generateArray(4.5))
console.log(generateArray(2.5))
console.log(generateArray(0.5))
console.log(generateArray(5))

To address precision concerns, a safeSubtract function has been included:

const safeSubtract = (n, i) => {
  const [int, dec = ''] = String(n).split('.')
  return +`${+int - i}.${dec}`
};

const generateArray = num => Array.from({ length: 5 }, 
  (_, i) =>  Math.max(Math.min(safeSubtract(num, i), 1), 0)
)

console.log(generateArray(4.8))
console.log(generateArray(2.8))
console.log(generateArray(0.8))
console.log(generateArray(5))

Answer №2

Important I have addressed the rounding problem that occurs when converting 0.8 to 0.7999999999999998 in some previous responses.

function convertNumber(n) {
  let [whole, dec] = ("" + n).split("."); // separating the number into whole and decimal parts
  let newArr = Array
    .from({length: 5})  // creating an array of length 5
    .fill(1, 0, whole)  // filling with 1s up to the whole number
    .fill(0, whole, 5); // filling with 0s for the remaining positions
  if (dec) newArr[whole] = +("." + dec); // adding decimal values if necessary
  return newArr;
}

// testing the function:
[2.8, .5, 5, 3, 4.789].map(n => console.log(n,":",...convertNumber(n)))

Answer №3

Start by getting the whole number and the decimal part of a number. Fill the initial positions of an array with 1s corresponding to the whole number portion. Then, insert the decimal at the following index. It's advisable to perform validations to ensure the number is below 5 (the array size);

    let newArr = [0, 0, 0, 0, 0];
    let num = 6.3;
    let whole = Math.floor(num);
    let decimalPart = num - whole;

    for(let j=0; j<whole; j++) {
       newArr[j] = 1;
    }
    newArr[whole] = decimalPart;

Answer №4

To find the value for each position, it is necessary to calculate it and determine the remainder for the next iteration.

function generateStars(value) {
    return Array.from({ length: 5 }, _ => Math.max(Math.min(value--, 1), 0));
}

console.log(...generateStars(0.5));
console.log(...generateStars(2));
console.log(...generateStars(2.8)); // rounding may be required...

Answer №5

UPDATED: I have addressed the rounding issues.

If you encounter rounding problems, you can utilize the numToArray function provided below:

function numToArray(num) {
  let intPart = Math.floor(num)
  let result = Array()
  for(let i = 0; i < intPart; i++) {
    result.push(1)
  }
  if(num > intPart) {
    result.push(Number((num - intPart).toFixed(2)))
  }
  return result
}


console.log(numToArray(2.8))
console.log(numToArray(4.5))
console.log(numToArray(0.8))
console.log(numToArray(4))

Answer №6

One possible approach could be:

let num = 3.8;
let array = [0, 0, 0, 0, 0];
let index = 0;
for (; num > 0; num--) {
array[index] = num >= 1 ? 1 : parseFloat(num.toFixed(10)); // Resolving floating-point issues in JavaScript
index++;
}
console.log(array);

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

When running `npm run dev` on webpack-dev-server, I encountered a TypeError stating that the property `port` cannot be set on an

Running node v10.15.1, vue js, vue-cli, and vue-loader with webpack, http-proxy-middleware (included) on a local win10 x64 remote host has been successful. Bootstrap v4 and bootstrap-vue were also installed and imported correctly. However, upon running np ...

Learn how to generate a dynamic pie chart in PHP that can adjust its sections based on the user's input, giving you a fully customizable data visualization tool

let userData = [ { label: "History", data: 90 }, { label: "Science", data: 85 }, { label: "Art", data: 95 }, ]; I have written this javascript code to represent the user's data, but I want it to be more flexible an ...

"Adding an image to create a border within a dropdown in Bootstrap 4: A step

I have been utilizing Bootstrap 4 navbar to construct my menu. Within my menu, there is a dropdown menu that I am seeking to customize. My goal is to adjust the top border of the dropdown menu so it resembles the design seen in this image. My attempt to i ...

Is it necessary to specify the JavaScript version for Firefox? (UPDATE: How can I enable `let` in FF version 44 and below)

Our recent deployment of JavaScript includes the use of the let statement. This feature is not supported in Firefox browsers prior to version 44, unless JavaScript1.7 or JavaScript1.8 is explicitly declared. I am concerned about the potential risks of usi ...

Solving yarn conflicts when managing multiple versions of a package

My software application contains a vulnerability related to a package that has different versions available (1.x, 2.x, 3.x). Since many other packages rely on this particular one as a dependency, updating each one individually is not a viable solution at t ...

How did my attempt to add a length() method to Object end up breaking jQuery?

Here is the code I created: Object.prototype.length = function(){ var count = -1; for(var i in this) count++; return count; } Surprisingly, when viewing my page with Firebug enabled, it gives an error stating that jQuery's .appendTo() is ...

What's the best way to unpack the gzip data that Ajax sends to JavaScript?

Hello there! I've encountered an issue: PHP is sending compressed data using gzdeflate(): $string=gzdeflate($string,9); echo $string; In the browser, pako.js has been included and the following code is executed: var rsp=rst.responseText; rsp=pako.in ...

I am facing difficulties displaying the egin{cases}…end{cases} equation using Jekyll's MathJax

MathJax is used on our course website. We have implemented MathJax in Jekyll and hosted it on GitHub pages. While MathJax works well for simple equations, I have faced difficulties with more complex ones. Despite spending hours investigating and experiment ...

Troubleshooting a Problem with AppCheck Firebase reCaptcha Configuration

Currently integrating Firebase with my Next.js project. I've been attempting to configure AppCheck reCaptcha following the documentation and some recommendations, but I encounter an issue when running yarn build The build process fails with the foll ...

Guide for retrieving the maximum length of an input field using JavaScript

Is it possible to retrieve the maxlength of an input field using JavaScript? <input type="password" id="password" maxlength="20" > I attempted to do this, however it only returns undefined console.log(document.getElementById("password").maxlength) ...

Unable to generate a new file via POST request in mongoose and express

Can someone please review my Node.js code? I am trying to save contact page data in Mongoose Compass. The code runs without any errors, but it's not saving the data. <form action="/" class="contact_form grid" method="POST& ...

Unusual display of feedback text in Bootstrap 4

When I directly copied this code snippet from Bootstrap 4: <div class="form-group has-danger"> <label class="form-control-label" for="inputDanger1">Input with danger</label> <input type="text" class="form-control form-contro ...

Documents are not stored in cache

Using the cache.manifest file, I am able to view my project offline and everything works perfectly. However, the only issue I'm facing is that the libraries for my gallery slider are not being cached, and I'm not sure why. Can anyone lend me a ...

Struggling to access component variables within the setTimeout function

As a newcomer to Angular(6), I am facing an issue where I am unable to access component variables within a setTimeout function. Below is the code snippet illustrating my problem. export class ConSellerDraftsolSecOneComponent implements OnInit { ...

When using jQuery, the script will execute successfully only when running it chunk by chunk in the console, rather than running the

As I tidy up an html page, my main task is to remove anchor tags and keep the text nodes. To achieve this, I am enclosing all text nodes (without any surrounding elements) within the <asdf> tag. Additionally, I am deleting empty elements such as < ...

ng-class will not activate a custom directive

I have developed a custom AngularJS directive that should work on elements with the specified class name .collapse. However, when I apply this class using Angular's ng-class directive, the custom collapse directive does not get activated. Here is a ...

Creating a HTML5 canvas animation of an emoticon winking to add a fun touch to your

Currently, I am facing a challenge in animating an emoticon that was initially sketched on canvas. While following a tutorial to implement draw and clear animations using frames, I haven't been able to achieve the desired outcome. With 6 frames of the ...

Is there a way to update and save both dependencies and devDependencies with a single command in Npm?

Is there a way to update multiple npm dependencies and save them to their respective locations in the package.json file? This is what my package.json looks like: { "dependencies": { "gulp": "^3.0.0" }, "devDependencies": { "gulp-eslint" ...

The table's content extends beyond the confines of the page

I have an HTML page where I am embedding an SSRS report. The report extends beyond the page as shown in the image below: This is the table that is generated: <table cellpadding="0" cellspacing="0" id="ctl00_MainContent_FiveYearReportViewer_fixedTable" ...

React Bootstrap always displays tooltips

I have integrated react-bootstrap into my project. I am currently attempting to keep a tooltip always displayed, but I am facing some challenges in achieving this. Below are the approaches I have tried so far: <Card style={{width: '10rem'}} ...