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

Using AngularJS for AJAX operations with dynamic PHP variables

I have an AngularJS code that is looping through an AJAX JSON response like this: <div ng-repeat="post in posts"> {{post.title}} {{post.url}} </div> It's working fine. How can I pass a PHP variable based on the JSON? Let's assume t ...

What is the best way to duplicate a text using a button in ReactJS?

Hey there, I'm working with an array and trying to figure out how to copy the text in a p element ({item.adress} => this is part of an array item) when a button is clicked. Could you lend me a hand? import classes from './CryptoBox.module.css& ...

Obtain the origin of the image using dots in Javascript

Sharing my experience with setting a background image using Javascript. Initially, I tried using two dots like this: .style.backgroundImage = "url('../images/image00.jpg')" However, it did not work as expected. So, I removed one dot: .style.ba ...

Guide: Generating a dynamic textbox on click event without needing to reload the page

I need assistance with the following form:- <form action=""> <table border="0"> <td colspan="2" class="instruction">Please select an option to search.</td> </table> <table> <tr> ...

The Next.js build version encounters an issue with 'auth' property being undefined and causes a failure

Our team has been happily working on a Next.js based website for the past few months. Everything was running smoothly without any major issues until yesterday when we encountered an error on the production version while using router.push: Cannot read prope ...

Filtering database records using a static dropdown list in MVC 5: A step-by-step guide

Is there a way to filter database records based on the columns QtyRecieved, QtyRecievedand Void using a static HTML dropdown list? The QtyRecieved and QtyRecievedand column are both decimal values, while Void is a boolean. This is what I have attempted: ...

Exploring Autocomplete Functionality with SQLite Integration in Flask

I have been searching for a solution to my problem without any success. My SQLite database contains electronic products, and I have a search box that allows users to search for products by typing in their name. However, I want to enhance the user experienc ...

"Trouble displaying specific events based on their IDs retrieved from the MySQL database

Each button in my list is associated with a specific person. Upon clicking a button, it directs to calendar.php?id=5 (where 5 is the personal id). I want the calendar to display the vacations scheduled for that particular id from the MySQL database. even ...

Tips for implementing a checkbox (with tick/untick functionality) as a replacement for a plus/minus toggle using HTML

Is it possible to use checkboxes instead of plus and minus signs for expanding and collapsing sections? Can the plus and minus symbols be incorporated into the checkbox itself, so that clicking on the checkbox toggles between plus and minus states? Any hel ...

The contact form fields shimmer as they transition in and out

I am currently working on a contact form that includes four input fields - name, phone, email, and message. The functionality I am looking to implement is that when I click on one input field, the other fields will fade by 30%, such as email, phone, and ...

Exploring the concept of generator functions in ES6

I'm grappling with understanding JS generators and why the asynchronous operations in the example below are returning undefined. I thought that using yield was supposed to wait for asynchronous calls to finish. function getUsers(){ var users; $.aj ...

Channeling requests from webpack dev server to .net MVC website

I am working on incorporating Vue into my .net MVC project. After installing Vue using the CLI, I included the following vue.config.js: module.exports = { devServer: { proxy: { '/': { target: 'http://mvcsite.local', ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...

Merge two nested JSON arrays by overriding the values of JSON A with those of JSON B

There are two JSON arrays that need to be compared. If the "id" property in Json A matches the "id" property in Json B, then override the values of the properties in Json A with the values of the properties in Json B. Here is the JSON A Array: { "com ...

Conduct a unit test to verify that a function successfully connects to an API and accurately stores the retrieved data in a variable

Currently, I am working on creating a unit test for my writing and JavaScript code. This area is still challenging for me, so I am in the process of learning how to do it correctly. The specific function I am focusing on makes an API call and then assigns ...

Utilize jQuery ajax to pull in data from an external website

I've been doing some research on using jQuery ajax to extract links from an external website, but I'm a bit lost on where to begin. I'm taking on this challenge just to push my skills and see what I can accomplish. While reading about the S ...

Problem: Values are not being posted with AJAX when using $(form).serialize()

I'm encountering an issue with submitting a form using AJAX. I initially tried to pass the data using $("#myForm").serialize(), but for some reason, the receiving page doesn't receive the data. Take a look at my form: <form id="myForm"> ...

React-Collapsible Compilation Error

Currently, I am working on a project that involves Spring and ReactJS. I am still new to front-end development. One of the tasks I am trying to accomplish is creating a simple accordion using "REACT-COLLAPSIBLE". The code I have written is quite straight ...

Parsing user input with a custom tokenizing function

As a C beginner, I'm currently facing an issue with tokenizing a "string" input in my code. Despite extensive manual review, I can't seem to pinpoint the bug. The goal is to tokenize the input for executing basic Linux commands as part of buildin ...

Is it possible to create a dynamic-length array in PineScript?

Is it possible to create an array in PineScript that can accept a variable number of inputs for drawing price levels? The number of levels needed may change daily, ranging from 5 to 7 or more. I am looking for a way to declare an array with at least 1 pa ...