Re-sorting with _.sortBy() eliminates additional 0s from decimal values (transforming 0.10 to 0.1 and beyond)

Here is an array that needs to be sorted:

var baseBetAmount = [
{
    val: 'OtherBaseBet',
    text: 'Other'
},
{
    val: 0.10,
    text: '$0.10'
},
{
    val: 0.20,
    text: '$0.20'
},
{
    val: 0.50,
    text: '$0.50'
},
{
    val: 1,
    text: '$1'
},
{
    val: 2,
    text: '$2'
}]

I have tried to sort it using the following function:

var options=  _.sortBy(baseBetAmount)

The output after sorting looks like this:

[
{
    val: 'OtherBaseBet',
    text: 'Other'
},
{
    val: 0.1,
    text: '$0.10'
},
{
    val: 0.2,
    text: '$0.20'
},
{
    val: 0.5,
    text: '$0.50'
},
{
    val: 1,
    text: '$1'
},
{
    val: 2,
    text: '$2'
}]

However, the issue is that numbers such as 0.10 are being replaced by 0.1 in the sorted array. I need help to prevent this from happening.

Answer №1

This is a viable solution, but it requires parsing the value for mathematical calculations.

var baseBetAmount = [
{
    val: 'OtherBaseBet',
    text: 'Other'
},
{
    val: 0.10,
    text: '$0.10'
},
{
    val: 0.20,
    text: '$0.20'
},
{
    val: 0.50,
    text: '$0.50'
},
{
    val: 1,
    text: '$1'
},
{
    val: 2,
    text: '$2'
}];

 var options = _.sortBy(baseBetAmount).map(function(base){
 if(_.isNumber(base.val)){
 base.val = base.val.toFixed(2);
 }
 return base;
 });

console.log(options);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
</body>
</html>

toFixed() converts the value to a string, so it must be parsed with parseFloat for any mathematical operations.

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

Add the item to an array to store its state

I have a state variable that is initially set as an empty array const [boxes, setBoxes] = useState([]); const [showAddGalley,setShowAddGalley]=useState({galleyNo:""}); I created a function to handle form submissions, where I want to update the b ...

What is the reason for jQuery displaying undefined when attempting to retrieve a custom data attribute using .prop()?

In my dynamic HTML generated by JavaScript, the following code snippet is included: $(".task-status").live("click", function () { alert("data-id using prop: " + $(this).prop("data-id")) alert("data-id using data: " + $(this).data("id")) ...

The submission of the Jquery form is not successful

I am struggling with a form on my page. I want to disable the submit button and display a custom message when submitted, then use jQuery to actually submit the form. <form> <input type="text" name="run"/> <input type=&quo ...

Different methods of transferring PHP post information to JavaScript

Is there a cleaner and more elegant way to pass posted PHP variables to JavaScript for manipulation, rather than using inline JavaScript? I currently have a simple PHP form that posts data to specific variables and then uses inline JavaScript to handle the ...

The entered value in the <input> field is not valid

I am encountering an issue where the input value is auto-filled, but when I click the submit button, the input field value is not recognized unless I modify something in it, such as deleting and adding the last word to the first name. Is there a way to m ...

Creating a dynamic user interface in Angular 6 that successfully tracks changes without reliance on the parent

As I delve into the world of Angular, I am faced with a challenge in creating a reusable component that will be bundled into an npm module. The issue lies in the UI change detection aspect. In order for the component to function properly, the application ...

What is the best way to set checkboxes to default values using a model?

My journey with angular.js continues as I embark on creating my first non-tutorial web app. In this endeavor, I am utilizing two smart-tables and checklist-model for a seamless user experience. The initial table uses a st-safe-src of all_types, containing ...

Moving information from two modules to the service (Angular 2)

Recently in my Angular2 project, I created two components (users.component and tasks.component) that need to pass data to a service for processing before sending it to the parent component. Code snippet from users.component.ts: Import { Component } fro ...

Is there a way to activate the autoplay feature for this?

I'm really new to Jquery and most of this code isn't mine, I'm just using it as a learning tool for creating sliders. If someone could give me some guidance on how to make this slider work automatically when the page loads, that would be gre ...

How can jQuery determine the amount of line breaks within a div element?

My div wrap size is a percentage of the screen width, containing multiple .item divs that break into new lines as the window size decreases. I attempted to calculate the total number of boxes that could fit based on their widths compared to the container ...

Encountering a TypeError while trying to run Pythonshell on my Mac device

When I run a python script in node.js using python shell, it works perfectly on my Windows system. However, I encounter an error when trying to run the same thing on my Macbook: Error: TypeError: can't multiply sequence by non-int of type 'float ...

Utilize v-for to dynamically showcase a variety of images on your

My goal is to showcase several JPG pictures located in the src/assets/images folder by utilizing the v-for directive. However, it seems like the browser is having trouble locating them. Interestingly, manually adding the pictures with the same paths works ...

What is the best way to remove an exported JavaScript file from Node.js?

In my Node.js library package called "OasisLib," there is a file named TypeGenerator.ts. The specific logic within the file is not crucial, but it requires access to files in the filesystem during the project build process. To achieve this, we utilized let ...

Passing parent props to child components in Vue.js - A comprehensive guide!

Trying to understand the process of passing a prop from parent to child components. If I include the prop attribute with the #id within the child component tag, like Image cid="488484-49544894-584854", it functions correctly. However, I am interested in u ...

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Exploring the world of data manipulation in AngularJS

Seeking to comprehend the rationale behind it, I will share some general code snippets: 1) Fetching data from a JSON file using the "loadData" service: return { myData: function(){ return $http.get(path + "data.json"); } } 2) ...

Updating route from action within Vuex Store

Exploring ways to trigger a route change from the store. I attempted to import router directly into the store and use the following code: LOG_OUT({commit}){ commit('LOG_OUT__MUTATION'); router.push({ name: 'Login' }) } Unfo ...

Updating inner text content dynamically can be accomplished without relying on the use of the eval() function

I am faced with a situation where I have multiple batches of code structured like this: 1 <div id="backgrounds" class="centery">Backgrounds 2 <div id="bk1" class="attr">Background 1 3 <div class="container"> 4 ...

Iterate through an array to extract specific objects and exclude them from another array

Within my code, I have an array named allItems that stores objects. allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ] I am seeking a way to filter out the objects from th ...

What is the best way to add items to arrays with matching titles?

I am currently working on a form that allows for the creation of duplicate sections. After submitting the form, it generates one large object. To better organize the data and make it compatible with my API, I am developing a filter function to group the du ...