Formatting Integer Arrays with JavaScript

My current project involves iterating through an array of floating point numbers. The goal is to format each float to a specific pattern ".XXX" where X represents a number. If the float begins with a 0, it should be excluded. For instance, 0.2867 should appear as .286, while 1.2 should become 1.200. In case an element in the array is not a number like "-", it should be displayed as .000.

I have shared my code for this task below but I seem to be stuck:

$( document ).ready(function() {

var statsArray = [0.2867, 0.833, 1.576, 0.19, 0.688, 0.22, 0.572, .167, 0.643, 0.921, "-", "-", 0.222, 1.466789, 0.1, 0.714, 1.115];

function formatter()
{
    var numElements = statsArray.length;

    for (var m=0; m <= numElements; m++) 
    {
        var arrayElement = statsArray[m];

        console.log ("original element is " + arrayElement);

        arrayElement = parseInt(arrayElement, 10);

        console.log ("after parseInt element is " + arrayElement);

        arrayElement = arrayElement.toPrecision(3);

        console.log ("after toPrecision element is " + arrayElement);

    }
}

formatter();

});

I would appreciate any suggestions on how to proceed or if there are any gaps in my approach! Thank you!

Answer №1

To verify the presence of "-", utilize the isNaN function; eliminate parseInt and = from the <= operator; establish an array for storing values, then retrieve the array from the formatter() function.

Amendment, Revised Version

In addition to the guidance provided by @JonathanLonowski, consider replacing .toPrecision() with .toFixed() to achieve the desired outcome.

var statsArray = [0.2867, 0.833, 1.576, 0.19, 0.688, 0.22, 0.572, .167, 0.643, 0.921, "-", "-", 0.222, 1.466789, 0.1, 0.714, 1.115];

function formatter(arr) {
  for (var m = 0, res = []; m < arr.length; m++) {
    var arrayElement = statsArray[m];
    console.log("original element is " + arrayElement);
    if (!isNaN(arrayElement)) {
      res.push(arrayElement.toFixed(3))
    } else {
      if (arrayElement === "-") {
        res.push(".000")
      }
    }
  }
  return res
}

var result = formatter(statsArray);
console.log(result)

Answer №2

Give this a shot:

let dataPoints = [12.2, 0.2867, 0.833, 1.576, 0.19, 0.688, 0.22, 0.572, .167, 0.643, 0.921, "-", "-", 0.222, 1.466789, 0.1, 0.714, 1.115];

dataPoints = dataPoints.map(function(num){
    num = Number(num).toFixed(3);

    if(num === 'NaN') return '.000';

    return num[0] === '0'? num.slice(0) : num;
});
console.log(dataPoints);

Check out the live codepen here: http://codepen.io/someuser/pen/example123

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

What is the method used for defining an element within an array in JavaScript?

As I am new to JavaScript, I find myself trying to organize callbacks within an array. An example of what I have been working on: items = [ "test" = async message => { let userCoins = editCurrency('fetch', message.guild. ...

Is there a way to adjust this validation logic so that it permits the entry of both regular characters and certain special characters?

Currently, the input field only accepts characters. If any other type of character is entered, an error will be thrown as shown in the code below. How can I update this logic to allow not only letters but also special characters like hyphens and apostrop ...

Please provide links to both the image and text within a Rails 3.1 application

Hey there! I have a small piece of code and I'm wondering how to add a link to both the icon and text. I am calling an icon from a class. Check out my code below: <td class="cv-class_<%= index + 1 %>"> <a onClick="ad ...

The Promise resolved with an undefined value

I'm encountering an issue and suspect that it may have to do with incorrect awaits or the challenge of resolving a promise within a wrapped callback function. I'm unsure how to address this problem. Any assistance would be greatly appreciated! as ...

I am encountering a challenge retrieving the ID via AJAX from the view to the controller. However, the ID is successfully displaying in the alert

In the view page code below, I am trying to send an ID through Ajax but it is not posting in the controller. The goal is to replace one question at a time fetching from the database. $(document).ready(function() { $("#next").click(function() { ...

Python itertools module causing time limit to be exceeded in 3sum implementation

Seeking a solution for finding unique triplets in an integer array nums that sum up to zero, excluding any duplicates where the indices i, j, and k are not equal. This problem requires optimization to improve efficiency and pass all test cases successfully ...

Troubleshooting: jQuery unable to locate element within iframe

I need help finding all elements within an iframe that contain a specific word, for example, 'stack' on this page: http://en.wikipedia.org/wiki/Stack_Overflow Here is the code I am currently using: <body> <iframe src="http://en.wik ...

Is there a way to choose multiple dropdown items that share the same header?

Utilizing the Fluent UI React Northstar Dropdown component in my React project, I've encountered an issue with multiple item selection. It seems that when there are several items sharing the same header value, only one can be selected at a time. What ...

I need a layout similar to the navbar on http://thecoloradan.com/ but I am not asking for instructions on how to do it

Have you seen the stunning navbar on this website? It appears to merge with the background upon loading, then smoothly shifts to the top of the page as you scroll. The transition is accompanied by a lovely animation. I am curious about the steps needed to ...

What are the methods to transmit various data formats in an AJAX POST request?

I am facing an issue with sending a JSON object along with two file upload objects to the controller in JavaScript. I have tried the following code snippet: data: {"jsonString":jsonString, "fd":"fd", "fd1":"fd1"}, Is there any other way to achieve this, ...

`The select list is not responding to the change event being triggered`

Here is an example of HTML code: <select id="v_name" align="top"> <option value="server1">server1</option> <option value="server2">server2</option> </select> And here is the corresponding JavaScript code: < ...

Tips for troubleshooting JavaScript tests in Node.js using breakpoints with Selenium WebDriver?

When writing my javascript tests in WebStorm, I incorporate Selenium WebDriver (along with chromedriver) to execute the tests in a browser. For test-runner framework, I rely on Mocha. The issue arises when: attempting to debug my tests and setting breakpo ...

Transform the features of a website into a sleek iOS application using Swift

Can I take an HTML website coded with JavaScript and integrate its functionality into my app using WebKit or another method? By using WebKit or WebViews, I can load an entire webpage into my app, automatically bringing along its functionality. However, i ...

Using Node.js to dissect a nested JSON array into individual JSON objects

Seeking guidance on how to efficiently parse nested arrays into separate objects using Node.js. Your assistance would be greatly appreciated. I aim to exclude the following from the final output- "Status": "0", "Message": "OK", "Count": "3724", AND I w ...

Encountering a hitch while attempting to integrate a framework in Angular JS 1

Having experience with Angular JS 1 in my projects, I have always found it to work well. However, I recently encountered a project that uses Python and Django, with some pages incorporating Angular. The specific page I needed to work on did not have any An ...

Retrieving data from the database without the need to reload the page

Hi there! I have a PHP script that fetches data from a database and I want to display this data within a div element with a "link" class without having to reload the page. Check out the code snippet below: <? include('config.php'); $rs = m ...

What methods can be used to search within one array in order to filter another array contained in a list?

Looking for suggestions on creating a filter in one list based on another list How can I handle filtering an array within a list by searching in another array? For example... myArray = [ { "name": "Item-A", "tags": ["Facebook" ...

What strategies can I implement to prevent security alerts in Internet Explorer 8 when accessing Google Maps via a secure connection

When using Google Maps on my project through an https connection, I encountered a problem. Interestingly, the issue only arises in certain browsers while others work fine. Despite searching for a solution extensively, I have not been able to find one. Some ...

Is it possible to customize the mounting element of NextJS or apply additional classes to the __next div?

In a nutshell, I'm currently working on a project where my aim is to make the content "fill" the vertical space below the static header. Previously, in React with tailwind, I achieved this like so: <body class="flex flex-col h-screen text-gray ...

Running a Node.js script on an Express.js server using an HTML button

I've got an HTML button: <button id="save" type="button" onclick="save()">Save</button> and in my JavaScript code, I want it to execute something on the server side using node.js Here's what I have in mind: function save() { / ...