The sorting of objects by Lodash is not accurate

My aim is to arrange objects based on a specific property (price).

var arr = [{
        name: 'Apple',
        price: '1.03'
    },
    {
        name: 'Cherry',
        price: '0.33'
    },
    {
        name: 'Mango',
        price: '0.53'
    }
]

Using lodash to sort the array by their prices:

arr = _.sortBy(arr, 'price' ).reverse();

After sorting, arr[0] should be Apple since it has the highest price, but that's not the case. What could possibly be the issue?

Answer №1

It seems that the current issue is due to sorting Strings, which may not yield the expected outcome. To properly sort based on price, you can utilize the following code snippet (or a similar approach):

var items = [{
        name: 'Apple',
        price: '1.03'
    },
    {
        name: 'Cherry',
        price: '0.33'
    },
    {
        name: 'Mango',
        price: '0.53'
    }
]

items.sort(function(a, b){
return parseFloat(b.price) - parseFloat(a.price);
});

console.log(items);

Answer №2

In this particular scenario where a Lodash solution is not readily available, I will provide one for the benefit of anyone who might come across this question in the future:

// Your code:
var arr = [{
        name: 'Apple',
        price: '1.03'
    },
    {
        name: 'Cherry',
        price: '0.33'
    },
    {
        name: 'Mango',
        price: '0.53'
    }
]

// The code that you attempted but didn't work as expected:
// arr = _.sortBy(arr, 'price' ).reverse();

const sortedArr = _.chain(arr)
  .map((val) => _.toNumber(val.price))
  .sortBy()
  .value();
  
console.log(sortedArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

Answer №3

When the price value inside each object is a string, it can lead to different results. To resolve this issue, you can utilize a function callback to convert the price value into a number and then use sortBy to arrange your data based on the numeric value of price.

var arr = [{name: 'Apple',price: '1.03'},{name: 'Cherry',price: '0.33'},{name: 'Mango',price: '0.53'}];
_.sortBy(arr, ({price}) => +price);
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

Answer №4

If you are utilizing LoDash library, this is the method I used:

var products = [{name: 'Apple', price: '1.03', weight:'12'},{name: 'Cherry', price: '0.33', 
weight:'12', weight:'12'},{name: 'Mango', price: '0.53', weight:'12'}];

sortBy(sortKey, sortType, sortOrder)
{

  if(sortType == 1)
  {
       _.orderBy(products, [function(item) { return parseFloat(item[sortKey]); }], sortOrder);
  }
  else
  {
      _.orderBy(products, [function(item) { return item[sortKey]; }], sortOrder);
  }
}

//To utilize the function:
sortBy("price", 1, "asc");
sortBy("weight", 1, "asc");
sortBy("name", 0, "desc");`

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 best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

Discovering the most recent messages with AJAX

I'm feeling a bit lost on this topic. I'm looking to display the most recent messages stored in the database. (If the messages are not yet visible to the user) Is there a way to achieve this without constantly sending requests to the server? (I ...

Avoid the need to refresh the HTML content every time there is a change in the Angular $

One of the challenges I'm facing is with a for loop in my JavaScript: for (var i=0;i<2;i++) { $scope.widget = widgets[i]; $scope.header = widgets[i].data.header; $scope.items = widgets[i].data.items; $scope.footer = widgets[i].data ...

Gathering information from a website where the URL remains constant even after clicking on a specific button

Visit this website for bus tickets: I am working on scraping data related to bus trips from the mentioned site. However, the data I need to scrape depends on the user-selected date in my web application. Does anyone have suggestions on how I can develop ...

Potential Cross-Origin Resource Sharing (CORS) problem arises when integrating Node Express with an Ionic

Currently, I have an Ionic application that communicates with a Node Express application using Restangular. Everything works smoothly when the Node Express server is configured to use HTTP. On the Ionic app side: RestangularProvider.setBaseUrl('http ...

Can an HTML DIV be resized along with its contents?

Is it possible to scale a container with animated elements inside to fit the browser window, or do you have to adjust each child element individually? ...

Displaying the number of tasks completed compared to the total number of tasks within a JavaScript ToDo list

Currently, I'm in the process of creating a basic ToDo list using HTML, JS, and CSS. The last task on my list is to display to the user the total number of tasks and how many have been completed. For instance, if there are 3 completed tasks out of 7 i ...

Utilizing MongoDB Data in an .ejs Template Using Node.js Express

After going through numerous tutorials, I find myself stuck at a point where I am struggling to render all the data written by my express-app into MongoDB in embedded JavaScript. My goal is to display this data in a simple table that always shows the updat ...

Extract core object from array of objects with lodash or javascript

In my code, I have an array of objects that each contain a base object with a set of values. My goal is to remove the base object from all the data and achieve the Expected result shown below. Here is an example of the array: [ { "100": { ...

Utilize a button within a form to add additional variables to a URL that already contains variables from a separate form

I operate a website that features a search bar and checkboxes for adding variables to the URL: term = "test" variable1=1 url/search?term=test&variable1=1 After completing the initial search, I have additional forms on the left side of the page with m ...

Stop the background from scrolling and prevent auto-jumping to the top on mobile devices

When users click on the hamburger icon in the top right of our mobile site, I want the drop-down menu to appear and be scrollable without the background scrolling. I tried using JavaScript to set the body to fixed when the menu icon is clicked, but this ca ...

Retrieve JSON Object using a string identifier

I created a script that takes the ID of a link as the name of a JSON dataset. $('.link').click(function() { var dataset = $(this).attr("id"); for (var i = 0; i < chart.series.length; i++) { chart.series[i].setData(lata.dataset ...

"Enhance your website with a backspace button using jquery - here's

Recently, I delved into the world of jQuery and decided to test my skills by creating a jQuery calculator. Everything worked perfectly except for the backspace button. This is what I tried: if (value === backspace) { $(input).val($(input).val().substring ...

"Error: React dotenv is unable to access the .env configuration file

My React and Node project has a .env file in the root directory, along with other important files like .eslint and .gitignore. The .env file contains 6 lines of code such as APIKEY=aeofiunoief, without any special symbols. Within the src/ directory, there ...

When a React Router link is activated, the React Bootstrap dropdown remains open instead of closing as expected

<NavDropdown className="userDropdownButton" title="dropdown" id="user-nav-dropdown" alignRight > <div className="userDropDown"> <Link to="/user" className="userDropDownheader"> user </Link> </div> < ...

Headers have already been sent to the client and cannot be reset

Although I am relatively new to using nodeJs, I have conducted research to troubleshoot my issue. However, it appears that I am struggling a bit with asynchronous functionalities. I came across a solution that unfortunately did not work as expected. Here i ...

Tips for validating a string in a URL with Selenium IDE

When I click on a tab on my website, it triggers an AJAX service call where the URL contains parameters related to the data being loaded after the tab is clicked. The data is displayed as horizontal tiles one below the other, with 4 tiles being loaded pe ...

Modify the form's action attribute when submitted

I am trying to create a form with multiple buttons that will change the action and target properties when a specific button is clicked. Below is my code snippet: <div id="root"> <form :action="form.action" ref="form" :target="form.target"&g ...

Can a Dashcode Webkit Web app be transformed into traditional HTML and CSS?

I have developed a blog using Dashcode, incorporating HTML, CSS, and Javascript to pull data from an xml file. It's pretty simple... My perspective on this is: 1. JavaScript should be compatible with all browsers (with some variations). 2. I may need ...

The functionality of TypeScript's .entries() method is not available for the type 'DOMTokenList'

I'm currently working with a stack that includes Vue3, Vite, and TypeScript. I've encountered an issue related to DOMTokenList where I'm trying to utilize the .entries() method but TypeScript throws an error saying Property 'entries&apo ...