What causes JavaScript parseFloat to add additional value in a for loop implementation?

I am facing a challenge where I need to convert an array of strings into an array of decimal numbers. The original array of strings is structured like this:

var array = ["  169.70", "  161.84", "  162.16", "  176.06", "  169.72", "  170.77", "  172.74", "  175.73", "    0.00", "    0.00", "    0.00", "    0.00"] 

To tackle this issue, I have written a concise function that parses each element of the array as shown below:

function parseFloatArray(array) {
    var parsedArray = [];
        for (var i = 0; i < array.length ; i++) {
            parsedArray[i] = parseFloat(array[i]);
            parsedArray.push(parsedArray[i]);           
            console.log(parsedArray[i]);
        };
    return parsedArray;
}

Upon inspecting the length of the array, it appears to contain 12 elements. Similarly, individual values are logged in the for loop showing 12 separate entries. However, when checking console.log(parsedArray), an additional zero appears at the end of the array despite displaying 12 values initially:

[169.7, 161.84, 162.16, 176.06, 169.72, 170.77, 172.74, 175.73, 0, 0, 0, 0, 0] 

I would appreciate any suggestions on how to enhance this function and insights on why the additional zero is appended even though the logs indicate only 12 elements present.

Answer №1

One way to optimize this is by using the array method map, which creates a new array with the values returned from a function (such as parseFloat):

var data = ["  169.70", "  161.84", "  162.16", "  176.06", "  169.72", 
"  170.77", "  172.74", "  175.73", "    0.00", "    0.00", "    0.00", "    0.00"];

var convertedData = data.map(parseFloat);
>>>value: (Array)     
[169.7, 161.84, 162.16, 176.06, 169.72, 170.77, 172.74, 175.73, 0, 0, 0, 0];

If you need to support browsers like IE<9, you can use a substitute for the map function-

Array.prototype.map = Array.prototype.map || function(callback, thisArg){
    var arr = this, len = arr.length, mappedArr = Array(len), index = 0;
    if(typeof callback === 'function'){
        while(index < len){
            if(index in arr){
                mappedArr[index] = callback.call(thisArg, arr[index], index, arr);
            }
            ++index;
        }
        return mappedArr;
    }
}

Answer №2

Only insert them one time:

function convertArrayToFloat(array) {
    var convertedArray = [];
    for (var i = 0; i < array.length; i++) {
        convertedArray.push(parseFloat(array[i]));
    }
    return convertedArray;
}

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

Passing the outcomes of several queries to a single route in my application, and displaying them on my

Currently, I am facing an issue with fetching 2 sets of data from my database using simple MongoDB queries. I need to pass both results to the view, but I am encountering an internal server error. My goal is to display a complete list of guardians along wi ...

What is the best way to add the current date to a database?

code: <?php session_start(); if(isset($_POST['enq'])) { extract($_POST); $query = mysqli_query($link, "SELECT * FROM enquires2 WHERE email = '".$email. "'"); if(mysqli_num_rows($query) > 0) { echo '<script&g ...

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

"My program crashes due to a bug in the code involving the use of

I am working on a code that displays the names of individuals from a list. The challenge arises when there are only one or no person signed up for a particular date. In such cases, if I create an array with an index beyond the limit of people, it crashes. ...

Using JQuery toggleclass to add transitioning effects to a :after element

I'm using the toggleClass function to add the class .expend to a div with an ID of #menu, which increases the height of the menu from 100px to 200px with a smooth transition effect. I also have a pseudo-element #menu:after for aesthetic purposes. My ...

An issue occurred while serializing or deserializing, specifically with the JavaScriptSerializer and

I am facing an issue while trying to retrieve images from my database. The process works smoothly with small images, but when attempting to do the same with the default Windows 7 images (Desert, Koala, Penguins, Tulips, etc.), I encounter an error: "Err ...

Using Jquery to access items in an array with associative keys

I'm attempting to arrange my list of locations based on shortest to longest distance using the following code snippet: for(var i=0; i<locations.length;i++) { var swapped = false; for(var j=locations.length; j>i+1;j--) { if ...

What is the best method for transferring a string from JavaScript to a JSON file?

Is there a way to update the value of "JSValue" in my JSON (JSValue) using JavaScript? Specifically, how can I assign JSValue to a variable called Value using JavaScript? JavaScript var Value = 1 + 1 JSON { "DATA": [ { "JSValue": "0" } ...

Tips for including arguments in pm2 file execution

What steps should I take to run the cluster.js file on pm2 successfully? When I try executing the file locally with 'node cluster.js 0 1' command, it appends two arguments but encountering an error when using 'pm2 start "cluster.js 0 1"&apos ...

The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below: <input matInput #inputSearch> @ViewChild('inputSearch', { static: false }) input: ElementRef; fromEvent(th ...

The HTML table is not fully filled with data from the XML file

Trying to populate an HTML table using XML data retrieved from an AJAX call is proving to be a challenge for me. The main issue I am facing is the inability to fully populate the HTML table. Being new to AJAX, understanding how XML interpretation works an ...

Mapping JSONP responses for jQuery UI autocomplete

Attempting to implement jqueryUI autocomplete. After alerting the response, it shows: ([ { "id": "test", "label": "test", "value": "test" } ]); However, when trying to map the result, the dropdown remains empty. Here is the code being used: <script> ...

What is the best way to manage a new Error in Node.js while utilizing ES6 Symbols?

In my node.js application, I am implementing an endpoint using ES6 Symbols. Here is an example: // ES6 Symbol Method const taskCreationMethod = { [Symbol.taskMethod]() { return { storeCheckFunc: async function(storeId, employeeId) ...

What is the efficient way to toggle localStorage based on checkbox selection using jquery?

I am looking to efficiently manage localStorage using checkboxes. When a checkbox is checked, I want to add the corresponding value to localStorage, and remove it when unchecked. var selectedModes = new Array(); $('.play_mode').on('click& ...

Rendering HTML is not supported by AngularJS on Android 19 with version 4.4.4 and Safari 8.0.5

I have been working on an AngularJS app that is being displayed in a Webview on Android. Everything was functioning properly until yesterday when I started encountering issues with Angular not rendering the DOM correctly. I have tested the app on various v ...

I'm receiving a Reference Error stating that 'next()' is not defined, despite the fact that I have defined it in my JavaScript code. What could be causing this issue?

I have a javascript function called next() to process information and then call the function from HTML. However, my Firefox console is showing a ReferenceError: 'next' is not defined. I am aware that there is an error in my code, but I cannot pin ...

What is an alternative method to retrieve form data without relying on bodyParser?

When it comes to accessing posted form data without using bodyParser, what alternatives are available? How exactly does bodyParser grant access to the data in req.body? Additionally, I am curious about the inner workings of this process on a deeper level. ...

"Extending Material-UI: Utilizing Multiple Snackbar Components

I've been struggling to display multiple warnings using Snackbar from the Material UI library in my React project. I haven't found any examples with React, only Vue. Can anyone help me with this? Here is the code that I have tried so far: https: ...

Using JavaScript to dynamically retrieve element IDs

Within the content on my page, there are multiple tables displaying product information along with their respective authors. Additionally, there is a div that contains hyperlinks for each author. Currently, I am linking the authors' names to hyperlink ...

"pre and post" historical context

Is there a way to create a stunning "Before and After" effect using full-sized background images? It would be amazing if I could achieve this! I've been experimenting with different examples but can't seem to get the second 'reveal' di ...